如何检查对象是否具有某些属性?例如:

>>> a = SomeClass()
>>> a.property
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'

如何在使用属性属性之前确定它是否具有属性属性?


当前回答

我想你要找的是哈萨特。然而,如果您想检测python财产,我建议您这样做-

try:
    getattr(someObject, 'someProperty')         
except AttributeError:
    print "Doesn't exist"
else
    print "Exists"

这里的缺点是财产__get__代码中的属性错误也会被捕获。

否则,请执行-

if hasattr(someObject, 'someProp'):
    #Access someProp/ set someProp
    pass

文件:http://docs.python.org/library/functions.html警告:我推荐的原因是hasattr无法检测财产。链接:http://mail.python.org/pipermail/python-dev/2005-December/058498.html

其他回答

尝试hasattr():

if hasattr(a, 'property'):
    a.property

请看下面zweiterlinde的回答,他提供了关于请求宽恕的好建议!一个非常蟒蛇的方法!

python中的一般做法是,如果属性大部分时间都可能存在,那么只需调用它,让异常传播,或者用try/except块捕获它。这可能比hasattr更快。如果属性可能在大多数时间都不存在,或者您不确定,那么使用hasattr可能会比重复陷入异常块更快。

我想你要找的是哈萨特。然而,如果您想检测python财产,我建议您这样做-

try:
    getattr(someObject, 'someProperty')         
except AttributeError:
    print "Doesn't exist"
else
    print "Exists"

这里的缺点是财产__get__代码中的属性错误也会被捕获。

否则,请执行-

if hasattr(someObject, 'someProp'):
    #Access someProp/ set someProp
    pass

文件:http://docs.python.org/library/functions.html警告:我推荐的原因是hasattr无法检测财产。链接:http://mail.python.org/pipermail/python-dev/2005-December/058498.html

对于字典以外的对象:

if hasattr(a, 'property'):
    a.property

对于字典,hasattr()将不起作用。

许多人都在告诉字典使用has_key(),但它已经贬值了。因此,对于字典,必须使用has_attr()

if a.has_attr('property'):
    a['property']
 

或者您也可以使用

if 'property' in a:

编辑:这种方法有严重的局限性。如果对象是一个可迭代的对象,它应该可以工作。请检查下面的评论。

如果您像我一样使用Python 3.6或更高版本,有一种方便的方法可以检查对象是否具有特定属性:

if 'attr1' in obj1:
    print("attr1 = {}".format(obj1["attr1"]))

然而,我不确定目前哪种方法是最好的。使用hasattr()、getattr(()或in。欢迎评论。

我建议避免这样做:

try:
    doStuff(a.property)
except AttributeError:
    otherStuff()

用户@jpalecek提到了这一点:如果doStuff()内部发生AttributeError,则表示您迷路了。

也许这种方法更好:

try:
    val = a.property
except AttributeError:
    otherStuff()
else:
    doStuff(val)