How to know if an object has an attribute in Python

前端 未结 14 2361
无人及你
无人及你 2020-11-22 12:19

Is there a way in Python to determine if an object has some attribute? For example:

>>> a = SomeClass()
>>> a.someProperty = value
>>         


        
14条回答
  •  生来不讨喜
    2020-11-22 13:14

    You can use hasattr() or catch AttributeError, but if you really just want the value of the attribute with a default if it isn't there, the best option is just to use getattr():

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

提交回复
热议问题