How to know if an object has an attribute in Python

前端 未结 14 2073
无人及你
无人及你 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
    
    0 讨论(0)
  • 2020-11-22 13:22

    You can check whether object contains attribute by using hasattr builtin method.

    For an instance if your object is a and you want to check for attribute stuff

    >>> class a:
    ...     stuff = "something"
    ... 
    >>> hasattr(a,'stuff')
    True
    >>> hasattr(a,'other_stuff')
    False
    

    The method signature itself is hasattr(object, name) -> bool which mean if object has attribute which is passed to second argument in hasattr than it gives boolean True or False according to the presence of name attribute in object.

    0 讨论(0)
提交回复
热议问题