gpt4 book ai didi

python - python中的嵌套try语句?

转载 作者:IT老高 更新时间:2023-10-28 22:02:51 33 4
gpt4 key购买 nike

有没有更好的方法来做以下事情:

try:
a.method1()
except AttributeError:
try:
a.method2()
except AttributeError:
try:
a.method3()
except AttributeError:
raise

它看起来很讨厌,我宁愿不这样做:

if hasattr(a, 'method1'):
a.method1()
else if hasattr(a, 'method2'):
a.method2()
else if hasattr(a, 'method3'):
a.method3()
else:
raise AttributeError

保持最大效率。

最佳答案

对第二个稍作改动看起来非常漂亮和简单。我真的怀疑你会注意到两者之间的任何性能差异,这比嵌套的 try/excepts 好一点

def something(a):
for methodname in ['method1', 'method2', 'method3']:
try:
m = getattr(a, methodname)
except AttributeError:
pass
else:
return m()
raise AttributeError

另一种非常易读的方法是......

def something(a):
try:
return a.method1()
except:
pass

try:
return a.method2()
except:
pass

try:
return a.method3()
except:
pass

raise AttributeError

虽然很长,但函数的作用非常明显。性能确实不应该成为问题(如果一些 try/except 语句显着减慢脚本速度,则脚本结构可能存在更大的问题)

关于python - python中的嵌套try语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/701466/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com