How to know if an object has an attribute in Python

前端 未结 14 2257
无人及你
无人及你 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 12:57

    hasattr() is the right answer. What I want to add is that hasattr() can also be used well in conjunction with assert (to avoid unnecessary if statements and make the code more readable):

    assert hasattr(a, 'property'), 'object lacks property' 
    

    As stated in another answer on SO: Asserts should be used to test conditions that should never happen. The purpose is to crash early in the case of a corrupt program state.

提交回复
热议问题