python isinstance vs hasattr vs try / except:什么更好? [英] python isinstance vs hasattr vs try/except: What is better?

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

问题描述

我正在设法确定不同方法之间的权衡,以确定对象 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.

就是这样说,你真的应该避免使用这样的,除了。这样做会捕获任何/所有异常,甚至是不相关的异常。相反,最好是捕获异常。

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:什么更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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