读书笔记, Python - python-tricks-buffet-awesome-features
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了读书笔记, Python - python-tricks-buffet-awesome-features,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1341字,纯文字阅读大概需要2分钟。
内容图文
![读书笔记, Python - python-tricks-buffet-awesome-features](/upload/InfoBanner/zyjiaocheng/841/1bbfd86862c0467db6c3e4b90518dee7.jpg)
1. assert
syntax: assert expression1 [",", expression2]
大致相当于
if __debug__:
if not expression1:
raise AssertionError(expression2)
例子1
def apply_discount(product, discount):
price = int(product['price'] * (1.0 - discount))
assert 0 <= price <= product['price']
return price
例子2
if cond == 'x':
do_x()
elif cond == 'y':
do_y()
else:
assert False, (
'This should never happen, 如果出现Heisenbug, 可以用这样的方式去debug
)
注意事项1: 可以用python -O
# 如果关闭assert, 很危险
def delete_product(prod_id, user):
assert user.is_admin(), 'Must be admin'
assert store.has_product(prod_id), 'Unknown product'
store.get_product(prod_id).delete()
应该改为
def delete_product(product_id, user):
if not user.is_admin():
raise AuthError('Must be admin to delete')
if not store.has_product(product_id):
raise ValueError('Unknown product id')
store.get_product(product_id).delete()
注意事项2: assert后面跟元祖, 永远为true. 不过python3会有提示
def hello_assert():
assert (1==2, 'This should fail')
# SyntaxWarning: assertion is always true, perhaps remove parentheses?
2. String literal concatenation, 双刃剑
这样就可以不用续行符了
my_str = ('This is a super long string constant '
'spread out across multiple lines. '
'And look, no backslash characters needed!')
Python’s string literal concatenation feature can work to your benefit, or introduce hard-to-catch bugs.
内容总结
以上是互联网集市为您收集整理的读书笔记, Python - python-tricks-buffet-awesome-features全部内容,希望文章能够帮你解决读书笔记, Python - python-tricks-buffet-awesome-features所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。
来源:【匿名】