0
什麼是僅在缺少方法時捕獲AttributeError
的最「pythonic」方法,而不是在後續調用該方法內的代碼中使用AttributeError
?我有這樣的代碼,它試圖調用的方法,並在缺少方法或一些預期異常的情況下,提供一些操作:只捕獲本地AttributeError(檢查方法是否存在並調用它時)
def foo(unknown_object):
try:
unknown_object.do_something()
except SomeSpecificError:
# the method existed, but failed in some expected way
except AttributeError:
# do something else ...
這個也有運行do_something()
捕AttributeError
,例如編程錯誤的問題(拼寫某些屬性錯誤)。這對於調試顯然不是很好,並且捕獲太多可能本身就是一個錯誤。我可以把它改寫成:
def foo(unknown_object):
try:
method=unknown_object.do_something
except AttributeError:
# do something else ...
else:
try:
method()
except SomeSpecificError:
# the method existed, but failed in some expected way
但是這是嵌套的解決方案,避免趕上太多AttributeError
的最Python的方式?
注意:該方法是丟失或贖回(或者它是一個編程錯誤,應提高捕獲的異常),所以我不需要檢查呼叫的能力。
是的,這就是我現在正在做什麼。或者(使用普通符號而不是hasattr所需的字符串)try:foo.attr,除了AttributeError:pass else:foo.attr()。但它似乎仍然是浪費的重複。 – pereric