rank vote view answer url
76 1183 605483 9 url

在 Python 中如何得到对象的所有属性?

有没有什么方法可以检测对象是否有一个属性?例如:

>>> 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()
Copyright © taizilongxu 2018 all right reserved,powered by Gitbook该文件修订时间: 2018-10-17 17:33:54

results matching ""

    No results matching ""