这是assert的四个简单调用:
>>> assert 1==2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError
>>> assert 1==2, "hi"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError: hi
>>> assert(1==2)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError
>>> assert(1==2, "hi")
请注意,最后一个不会引发错误。调用带或不带括号的assert导致此行为之间有什么区别?我的做法是使用括号,但以上内容表明我不应该这样做。
如果您通过完整的解释程序而不是通过IDLE运行最后一个命令assert
,则会给您一个警告(SyntaxWarning: assertion is always true, perhaps remove parentheses?
)。因为assert
是一个关键字而不是一个函数,所以实际上您将元组作为第一个参数传递而忽略了第二个参数。
回想一下,非空元组的计算结果为True
,并且由于断言消息是可选的,因此您在assert True
编写时实际上已经进行了调用assert(1==2, "hi")
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句