有没有更好的方法来做到以下几点:
try:
a.method1()
except AttributeError:
try:
a.method2()
except AttributeError:
try:
a.method3()
except AttributeError:
raise
Run Code Online (Sandbox Code Playgroud)
它看起来很讨厌,我宁愿不这样做:
if hasattr(a, 'method1'):
a.method1()
else if hasattr(a, 'method2'):
a.method2()
else if hasattr(a, 'method3'):
a.method3()
else:
raise AttributeError
Run Code Online (Sandbox Code Playgroud)
保持最高效率.