rank | vote | view | answer | url |
---|---|---|---|---|
71 | 1679 | 895303 | 14 | url |
有没有什么方法可以检测对象是否有一个属性?例如:
>>> a = SomeClass()
>>> a.someProperty = value
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
怎么样才能在用 porperty
之前知道 a
有这个属性?
试试 hasattr():
if hasattr(a, 'property'):
a.property
答案2
hasattr
可以做到,但是我要说一句 Python 鼓励 "easier to ask for forgiveness than permission" (EAFP) 而不是 "look before you leap" (LBYL).详细查看下面链接:
EAFP vs LBYL (was Re: A little disappointed so far) 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()