How to know if an object has an attribute in Python

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

提交回复
热议问题