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

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

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


当前回答

这里有一个非常直观的方法:

if 'property' in dir(a):
    a.property

如果a是字典,您可以正常检查

if 'property' in a:
    a.property

其他回答

这里有一个非常直观的方法:

if 'property' in dir(a):
    a.property

如果a是字典,您可以正常检查

if 'property' in a:
    a.property

对于字典以外的对象:

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

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

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

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

或者您也可以使用

if 'property' in a:

希望您希望使用hasattr(),但尽量避免使用hasattr(),请选择getattr(。getattr()比hasttr()快

使用hasattr():

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

同样,我在这里使用getattr获取属性,如果没有属性,则返回none

   property = getattr(a,"property",None)
    if property:
        print property

hasattr()是正确的答案。我想补充的是,hasattr()可以很好地与assert结合使用(以避免不必要的if语句,并使代码更可读):

assert hasattr(a, 'property'), 'object lacks property' 
print(a.property)

如果缺少属性,程序将退出并显示AssertionError,并打印出提供的错误消息(在这种情况下,对象缺少属性)。

如SO的另一份答复所述:

断言应该用于测试不应该发生的条件。目的是在程序状态损坏的情况下尽早崩溃。

通常情况下,如果缺少属性,那么断言是非常合适的。

根据pydoc,hasattr(obj,prop)只是调用getattr(obj,prop)并捕获异常。因此,用try语句包装属性访问并捕获AttributeError与预先使用hasattr()一样有效。

a = SomeClass()
try:
    return a.fake_prop
except AttributeError:
    return default_value