断言是什么意思?它是如何使用的?
当前回答
我的简单解释是:
如果表达式为假,assert会引发AssertionError,否则只是继续代码,如果有逗号,无论它是什么,它都会在逗号后引发AssertionError: whatever,而to code则是:引发AssertionError(逗号后的whatever)
相关教程:
https://www.tutorialspoint.com/python/assertions_in_python.htm
其他回答
assert语句有两种形式。
简单形式assert <expression>相当于
if __debug__:
if not <expression>: raise AssertionError
扩展形式assert <expression1>, <expression2>等价于
if __debug__:
if not <expression1>: raise AssertionError(<expression2>)
def getUser(self, id, Email):
user_key = id and id or Email
assert user_key
可用于确保在函数调用中传递参数。
Python assert基本上是一种调试辅助工具,用于测试代码内部自检的条件。 当代码进入不可能的边缘情况时,Assert使调试变得非常容易。断言检查那些不可能的情况。
假设有一个函数计算商品折扣后的价格:
def calculate_discount(price, discount):
discounted_price = price - [discount*price]
assert 0 <= discounted_price <= price
return discounted_price
这里,discounted_price永远不能小于0并且大于实际价格。因此,如果上述条件被违反,assert将引发断言错误,这有助于开发人员识别发生了不可能的事情。
希望能有所帮助。
如果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
正如其他答案所指出的,assert类似于在给定条件不为真时抛出异常。一个重要的区别是,如果使用优化选项-O编译代码,断言语句将被忽略。文档说断言表达式可以更好地描述为等效于
if __debug__:
if not expression: raise AssertionError
如果你想彻底测试你的代码,然后在你高兴地看到你的断言案例都没有失败时发布一个优化版本,这可能是有用的——当优化打开时,__debug__变量变成False,条件将停止计算。如果您依赖断言,而没有意识到断言已经消失,该特性还可以发现这一点。