断言是什么
Python assert(断言)用于判断一个表达式,在表达式条件为 false 的时候触发异常。
运用断言
example1(商店打折):
def apply_discount(product, discount):
price = int(product['price'] * (1.0 - discount))
assert 0 <= price <= product['price']
print(price)
shoes = {'name': 'nike', 'price': 1499}
apply_discount(shoes,0.25)
=> 1124
apply_discount(shoes,2)
=> Traceback (most recent call last):
File "/Users/sangyuming/Desktop/test.py", line 20, in <module>
apply_discount(shoes, 2.5)
File "/Users/sangyuming/Desktop/test.py", line 13, in apply_discount
assert 0 <= price <= product['price']
AssertionError
example2(判断类型):
type_str = 'asdfasdf'
assert type(type_str) == str
=>
assert type(type_str) == int
=>
Traceback (most recent call last):
File "/Users/sangyuming/Desktop/test.py", line 24, in <module>
assert type(type_str) == int
AssertionError
断言语法
assert [表达式]
等价于:
if not [表达式]:
raise AssertionError
由此可知,[表达式] 实际是if的判断语句
使用场景
断言不可不用,但也不能乱用
常见错误的用法是把断言当做一个检测错误的的触发条件,把它当做try..except
正确的使用场景如下:
- 在代码测试时使用
- 对代码单元逻辑的检测
- 对于复杂程序的类型、常量、条件的检测
原文地址:https://www.cnblogs.com/sangyuming/p/11686797.html
时间: 2024-11-25 16:43:15