断言是什么意思?它是如何使用的?
当前回答
>>>this_is_very_complex_function_result = 9
>>>c = this_is_very_complex_function_result
>>>test_us = (c < 4)
>>> #first we try without assert
>>>if test_us == True:
print("YES! I am right!")
else:
print("I am Wrong, but the program still RUNS!")
I am Wrong, but the program still RUNS!
>>> #now we try with assert
>>> assert test_us
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
assert test_us
AssertionError
>>>
其他回答
正如C2 Wiki上简要总结的那样:
断言是程序中特定位置的布尔表达式,除非程序中存在错误,否则该表达式将为真。
您可以使用断言语句来记录您对特定程序点上代码的理解。例如,您可以记录关于输入(前提条件)、程序状态(不变量)或输出(后置条件)的假设或保证。
如果断言失败,这是对您(或您的后继者)的一个警告,说明您在编写程序时对程序的理解是错误的,并且可能包含一个错误。
有关更多信息,John Regehr有一篇关于断言的使用的精彩博客文章,它也适用于Python断言语句。
这是一个简单的例子,保存到文件(比如b.py)
def chkassert(num):
assert type(num) == int
chkassert('a')
当$python b.py
Traceback (most recent call last):
File "b.py", line 5, in <module>
chkassert('a')
File "b.py", line 2, in chkassert
assert type(num) == int
AssertionError
>>>this_is_very_complex_function_result = 9
>>>c = this_is_very_complex_function_result
>>>test_us = (c < 4)
>>> #first we try without assert
>>>if test_us == True:
print("YES! I am right!")
else:
print("I am Wrong, but the program still RUNS!")
I am Wrong, but the program still RUNS!
>>> #now we try with assert
>>> assert test_us
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
assert test_us
AssertionError
>>>
assert语句几乎存在于每一种编程语言中。它有两个主要用途:
它有助于在程序的早期(原因很清楚的时候)检测问题,而不是在其他一些操作失败的时候。例如,Python中的类型错误如果没有在早期被捕获,可能会在实际引发异常之前经历几层代码。 对于阅读代码的其他开发人员来说,它可以作为文档使用,他们看到断言后可以自信地说从现在开始它的条件是成立的。
当你……
assert condition
... 您告诉程序测试该条件,如果条件为假,则立即触发一个错误。
在Python中,它大致相当于:
if not condition:
raise AssertionError()
在Python shell中试试:
>>> assert True # nothing happens
>>> assert False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
断言可以包含可选的消息,您可以在运行解释器时禁用它们。
如果断言失败,打印一条消息:
assert False, "Oh no! This assertion failed!"
不要像调用函数一样使用括号来调用assert。这是一个声明。如果执行断言(condition, message),则运行断言时将使用(condition, message)元组作为第一个参数。
至于禁用它们,当以优化模式运行python时,其中__debug__为False, assert语句将被忽略。只需要传递-O标志:
python -O script.py
相关文档请参见这里。
从文档:
断言语句是向程序中插入调试断言的一种方便方法
你可以在这里阅读更多:http://docs.python.org/release/2.5.2/ref/assert.html
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录