【发布时间】:2010-10-16 15:11:24
【问题描述】:
有没有更好的方法来做以下事情:
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
保持最大效率。
【问题讨论】:
-
您是否测试过您的理论,即第二种选择效率低下?如果它不比第一个更有效,我会感到惊讶。
-
Oddthinking 可能是正确的。 hasattr 消除了引发异常的需要。
-
其实hasattr()的实现本质上只是调用getattr(),如果抛出异常则返回False;见svn.python.org/view/python/tags/r254/Python/…
-
但这并不意味着第二个不会更快。这取决于第一种方法是否可能存在。
-
-1:过早的优化。为什么要担心性能?第一个显然是你的意思——只要这样做,不要在“效率”上狡辩,直到你能证明例外是你的瓶颈。