How to know if an object has an attribute in Python

前端 未结 14 2344
无人及你
无人及你 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:06

    According to pydoc, hasattr(obj, prop) simply calls getattr(obj, prop) and catches exceptions. So, it is just as valid to wrap the attribute access with a try statement and catch AttributeError as it is to use hasattr() beforehand.

    a = SomeClass()
    try:
        return a.fake_prop
    except AttributeError:
        return default_value
    

提交回复
热议问题