How to know if an object has an attribute in Python

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

    Try hasattr():

    if hasattr(a, 'property'):
        a.property
    

    EDIT: See zweiterlinde's answer below, who offers good advice about asking forgiveness! A very pythonic approach!

    The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than hasattr. If the property is likely to not be there most of the time, or you're not sure, using hasattr will probably be faster than repeatedly falling into an exception block.

提交回复
热议问题