断言是什么意思?它是如何使用的?
当前回答
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
如果assert后的语句为真,则程序继续执行,但如果assert后的语句为假,则程序报错。就这么简单。
例如:
assert 1>0 #normal execution
assert 0>1 #Traceback (most recent call last):
#File "<pyshell#11>", line 1, in <module>
#assert 0>1
#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对表达式求值。如果语句不为真,则引发异常(assertionError)。 如果断言失败,Python使用ArgumentExpression作为AssertionError的参数。可以像使用try-except语句一样捕获和处理AssertionError异常,但如果没有处理,它们将终止程序并产生跟踪。 例子:
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
当执行上面的代码时,它会产生以下结果:
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
assert语句有两种形式。
简单形式assert <expression>相当于
if __debug__:
if not <expression>: raise AssertionError
扩展形式assert <expression1>, <expression2>等价于
if __debug__:
if not <expression1>: raise AssertionError(<expression2>)
推荐文章
- 得到熊猫栏目的总数
- 从pandas DataFrame中删除名称包含特定字符串的列
- Mock vs MagicMock
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- 如何在matplotlib更新一个情节
- TypeError: ` NoneType `对象在Python中不可迭代
- 'throw'和'throw new Exception()'的区别
- 如何在Vim注释掉一个Python代码块
- python标准库中的装饰符(特别是@deprecated)
- 如何从外部访问本地Django web服务器
- 删除字符串的最后3个字符
- 在python中执行no-op的标准方法是什么?