Python assert 断言
来源:互联网 发布:qq微商软件 编辑:程序博客网 时间:2024/05/31 19:35
Python assert 断言
使用语法为:
assert expression [, arguments]
当expression为False时,触发异常,并返回arguments。在这里的arguments可以为字符串或者其他表达式等。
例1(无参数):
def test(a): assert len(a)<10, a = [x for x in range(20)]test(a)
例1错误信息为:
Traceback (most recent call last): File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 5, in <module> test(a) File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 2, in test assert len(a)<10AssertionError
例2(参数为字符串):
def test(a): assert len(a)<10, 'Input is too long'a = [x for x in range(20)]test(a)
例2错误信息为:
Traceback (most recent call last): File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 7, in <module> test(a) File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 4, in test assert len(a)<10, 'Input is too long'AssertionError: Input is too long
例3(参数为表达式):
个人想法:可以利用表达式这个特性,来动态地根据错误发生的实际情况来产生不同的错误信息,以便更好地来查找错误。
def test(a): assert len(a)<10, 'The length of input is ' + str(len(a)) + ' , and we just need 10.'a = [x for x in range(20)]test(a)
例3错误信息为:
Traceback (most recent call last): File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 7, in <module> test(a) File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 4, in test assert len(a)<10, 'The length of input is ' + str(len(a)) + ' , and we just need 10.'AssertionError: The length of input is 20 , and we just need 10.
assert 和 if not … raise 实现相同功能:
例4:
def test(a): if not len(a)<10: raise ValueErrora = [x for x in range(20)]test(a)
例4错误信息:
Traceback (most recent call last): File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 8, in <module> test(a) File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 5, in test raise ValueErrorValueError
阅读全文
0 0
- python assert断言
- python 断言assert用法
- python中的断言assert
- Python assert 断言函数
- Python 断言assert用法
- Python:断言(assert)
- Python assert 断言
- python使用assert断言
- Python assert断言
- python assert 断言语句
- python assert断言语句
- Python 断言(assert)
- python assert断言
- Python :assert断言使用
- [Python]断言assert的用法
- 每天一点python--assert断言
- Python 断言assert的使用
- python断言(assert) 与 __debug__
- STM32串口如何代码实现更稳定的接收消息
- 自定义圆形渐变加载百分比-开始-暂停
- React细节
- C的抽卡小游戏
- TF-IDF特征提取 用sklearn提取tfidf特征
- Python assert 断言
- android 多点触摸
- SQLite学习(二)
- java 多线程访问共享变量不安全因素分析
- SLAM学习——李群与李代数
- js代码规范
- HDU
- 揭开跨域的面纱(下)
- 期末算法作业