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

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

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


当前回答

根据情况,您可以检查您拥有的对象类型,然后使用相应的属性。随着Python 2.6/3.0中抽象基类的引入,这种方法也变得更加强大(基本上,ABC允许更复杂的鸭子类型)。

一种有用的情况是,如果两个不同的对象具有相同名称但含义不同的属性。仅使用hasattr可能会导致奇怪的错误。

一个很好的例子是迭代器和可迭代器之间的区别(参见这个问题)。迭代器和可迭代器中的__iter_方法具有相同的名称,但在语义上完全不同!因此,hasattr是无用的,但它与ABC一起提供了一个干净的解决方案。

然而,我同意在大多数情况下,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

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

使用hasattr():

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

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

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

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

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

我建议避免这样做:

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

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

也许这种方法更好:

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

您可以使用hasattr()或catch AttributeError,但如果您真的只希望属性的值具有默认值(如果不存在),最好的选择就是使用getattr(

getattr(a, 'property', 'default value')