¿Existe una manera más agradable de hacer lo siguiente:Declaraciones de prueba anidadas en python?
try:
a.method1()
except AttributeError:
try:
a.method2()
except AttributeError:
try:
a.method3()
except AttributeError:
raise
se ve bastante desagradable y que preferiría no hacerlo:
if hasattr(a, 'method1'):
a.method1()
else if hasattr(a, 'method2'):
a.method2()
else if hasattr(a, 'method3'):
a.method3()
else:
raise AttributeError
para mantener la máxima eficiencia.
¿Has probado tu teoría de que la segunda opción es ineficiente? Me sorprendería si no fuera más eficiente que el primero. – Oddthinking
Oddthinking es probablemente correcto. hasattr elimina la necesidad de que se levante una excepción. –
En realidad, la implementación de hasattr() básicamente solo llama a getattr() y devuelve False si se produce una excepción; ver http://svn.python.org/view/python/tags/r254/Python/bltinmodule.c?view = markup – Miles