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

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

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


当前回答

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

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

其他回答

我建议避免这样做:

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

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

也许这种方法更好:

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

正如贾雷特·哈迪回答的那样,哈沙特会做这个把戏。不过,我想补充一点,Python社区中的许多人建议采用“请求宽恕比请求许可更容易”(EAFP)而不是“三思而后行”(LBYL)的策略。参见以下参考文献:

EAFP vs LBYL(Re:到目前为止有点失望)EAFP与LBYL@代码如蟒蛇:惯用Python

ie:

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

…优先于:

if hasattr(a, 'property'):
    doStuff(a.property)
else:
    otherStuff()

尝试hasattr():

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

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

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

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

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

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

if 'property' in a:
    a.property

您可以使用hasattr内置方法检查对象是否包含属性。

对于一个实例,如果您的对象是,并且您想检查属性

>>> class a:
...     stuff = "something"
... 
>>> hasattr(a,'stuff')
True
>>> hasattr(a,'other_stuff')
False

方法签名本身是hasattr(object,name)->bool,这意味着如果对象具有传递给hasattr中的第二个参数的属性,则根据对象中name属性的存在,它会给出布尔值True或False。