我试图找出不同方法之间的权衡,以确定是否使用对象 obj
可以执行操作 do_stuff()
.据我了解,有三种方法可以确定这是否可行:
I am trying to figure out the tradeoffs between different approaches of determining whether or not with object obj
you can perform action do_stuff()
. As I understand, there are three ways of determining if this is possible:
# Way 1
if isinstance(obj, Foo):
obj.do_stuff()
# Way 2
if hasattr(obj, 'do_stuff'):
obj.do_stuff()
# Way 3
try:
obj.do_stuff()
except:
print 'Do something else'
首选方法是什么(为什么)?
Which is the preferred method (and why)?
我相信最后一种方法通常是 Python 程序员首选的,因为 座右铭 在 Python 社区中教授:请求原谅比请求许可更容易"(EAFP).
I believe that the last method is generally preferred by Python coders because of a motto taught in the Python community: "Easier to ask for forgiveness than permission" (EAFP).
简而言之,座右铭的意思是避免在做某事之前检查您是否可以做某事.相反,只需运行该操作.如果失败,请适当处理.
In a nutshell, the motto means to avoid checking if you can do something before you do it. Instead, just run the operation. If it fails, handle it appropriately.
另外,第三种方法还有一个额外的好处,就是明确操作应该起作用.
Also, the third method has the added advantage of making it clear that the operation should work.
话虽如此,您确实应该避免使用像这样的纯 except
.这样做将捕获任何/所有异常,甚至是不相关的异常.相反,最好专门捕获异常.
With that said, you really should avoid using a bare except
like that. Doing so will capture any/all exceptions, even the unrelated ones. Instead, it is best to capture exceptions specifically.
在这里,您需要捕获 AttributeError
:
Here, you will want to capture for an AttributeError
:
try:
obj.do_stuff() # Try to invoke do_stuff
except AttributeError:
print 'Do something else' # If unsuccessful, do something else
这篇关于python isinstance vs hasattr vs try/except:什么更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!