How to know if an object has an attribute in Python

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

    Hope you expecting hasattr(), but try to avoid hasattr() and please prefer getattr(). getattr() is faster than hasattr()

    using hasattr():

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

    same here i am using getattr to get property if there is no property it return none

       property = getattr(a,"property",None)
        if property:
            print property
    

提交回复
热议问题