在 Python 中,可以使用单行代码以一种简单、直观的方式设置具有特殊条件(例如默认值或条件)的值。
result = 0 or "Does not exist." # "Does not exist."
result = "Found user!" if user in user_list else "User not found."
是否可以编写一个捕获异常的类似语句?
from json import loads
result = loads('{"value": true}') or "Oh no, explosions occurred!"
# {'value': True}
result = loads(None) or "Oh no, explosions occurred!"
# "Oh no, explosions occurred!" is desired, but a TypeError is raised.
原文由 2Cubed 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 python 中不可能做一行异常处理语句。可以编写一个函数来执行此操作。
用法示例:
支持多个参数
错误捕获过程可能仍然被中断:
如果不需要此行为,请使用
BaseException
: