蟒蛇isinstance VS hasattr VS的try /除外:什么是好? [英] python isinstance vs hasattr vs try/except: What is better?

查看:137
本文介绍了蟒蛇isinstance VS hasattr VS的try /除外:什么是好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出不同的权衡决定您是否可以执行对象的某些动作,这些不同的方法:

I am trying to figure out the various tradeoffs for these various approaches of determining whether or not you can perform some action on an object:

# 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'

这是preferred方法(为什么)?

Which is the preferred method (and why)?

推荐答案

我相信,最后的方法一般是美元的,因为一个Python codeRS pferred p $的座右铭的讲授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.

随着中说,你真的应该避免使用裸除了这样。这样做将捕获任何/所有的异常,即使是无关的内容。相反,它是最好的特异性捕捉异常。

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

这篇关于蟒蛇isinstance VS hasattr VS的try /除外:什么是好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆