python 中的assert 可以简化代码,让python看起来如此简单、优雅
一般我们做判断,并抛出异常,实现是:
def raise_example(n):
if not n > 5:
raise Exception('num is littel than five')
如果使用assert 那么就更简单而高效了:
def assert_try(n):
assert n > 5, 'num is littel than five'
------------------------------------------------
Traceback (most recent call last):
File "/Users/Desktop/code/assert.py", line 15, in <module>
assert_try(3)
File "/Users/Desktop/code/assert.py", line 10, in assert_try
assert n > 5, 'num is littel than five'
AssertionError: num is littel than five
Process finished with exit code 1
使用场景:
- 检查参数类型,类或值
- 检查数据结构不变量
- 检查“不可能发生”的情况(列表中的重复,相互矛盾的状态变量。)
- 在调用函数之后,确保其返回是合理的