jibkfv 2019-07-28
最近每日一更,我这菜鸡都有点儿不好意思了
简单用法是:
assert expression
让我们用程序来测试这个expression
,如果expression
相当于False
,那么raise
一个AssertionError
出来。
即逻辑上等同于:
if not expression: raise AssertionError
简单看看这些例子:
>>> assert True >>> assert False Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> assert False AssertionError >>> assert 1==1 >>> assert 1==0 Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> assert 1==0 AssertionError >>> assert [1, 2] # 非空列表值得注意一下,虽说也没个啥,哈哈 >>> assert not [1, 2] Traceback (most recent call last): File "<ipython-input-48-eae410664122>", line 1, in <module> assert not [1, 2] AssertionError
assert
的异常参数,其实就是在断言表达式后添加字符串信息,一般用来解释断言。格式如下:
assert expression [, arguments] assert 表达式 [, 参数]
举例请看之后的代码
老铁们可以试着运行一下以下代码段:
>>> assert None, 'None若作为布尔表达式,则相当于False' >>> assert [], '空列表若作为布尔表达式,则相当于False' >>> assert (), '空元组若作为布尔表达式,则相当于False' >>> assert {}, '空字典若作为布尔表达式,则相当于False' >>> assert set(), '空集合若作为布尔表达式,则相当于False' >>> assert '', '空字符串若作为布尔表达式,则相当于False'
当然还有奇葩的numpy
>>> a = np.array([1, 2]) >>> assert a Traceback (most recent call last): File "<ipython-input-45-63e954d94e9b>", line 1, in <module> assert aa ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
是的,你没看错,哪里有numpy
,哪里就有Use a.any() or a.all()
......
最后,再试一试这俩吧:
>>> assert np.array([]) >>> assert np.array([[], []])
是的,只要是空的,甭管是几维的,都相当于False