在python中,断言是个很有趣的用法,今天总结一下:
在官方文档中:https://docs.python.org/3/reference/simple_stmts.html#assert ;
含义
所谓断言,就是一个确信的事情,在某个程序片段运行中,我确信某个条件会一直为真,那么我就可以用断言来“判断”他,一旦它不为真,就会报错。
用法
例如下面一个代码片:
s = 'foobar'
assert 'b' not in s
assert 'x' not in s
assert 'foo' in s
它的运行结果是:
AssertionError Traceback (most recent call last)
in ()
1 s = ‘foobar’
—-> 2 assert ‘b’ not in s
3 assert ‘x’ not in s
4 assert ‘foo’ in s
AssertionError:
很明显:第一个断言不为真,第二三个断言都是真,那么对应的,第一个断言报了一个AssertionError,二三个并没报错。
AssertionError:当assert断言条件为假的时候抛出的异常。
在官方文档中,有个解释断言的,二者逻辑一致:
if not condition:
raise AssertionError()
用处
关于用处,我找到了一个大牛翻译的文章,可以参考一下,点这里
本文是博主原创,转载请注明出处。