如何知道一个对象在Python中是否有属性?

2022-09-05 00:50:28

如何确定对象是否具有某些属性?例如:

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

在使用之前,您如何判断是否具有该属性?aproperty


答案 1

Try hasattr()

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

请参阅下面的zweiterlinde的答案,他提供了有关请求宽恕的好建议!一个非常蟒蛇的方法!

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


答案 2

正如Jarret Hardie所回答的那样,将做到这一点。不过,我想补充一点,Python社区中的许多人建议采用“比许可更容易请求宽恕”(EAFP)的策略,而不是“在你跳跃之前先看看”(LBYL)。请参阅以下参考资料:hasattr

EAFP vs LBYL(到目前为止是Re:有点失望)
EAFP vs. LBYL @Code Like a Pythonista: Idiomatic Python

结婚

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

...首选:

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