How to know if an object has an attribute in Python

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

    Depending on the situation you can check with isinstance what kind of object you have, and then use the corresponding attributes. With the introduction of abstract base classes in Python 2.6/3.0 this approach has also become much more powerful (basically ABCs allow for a more sophisticated way of duck typing).

    One situation were this is useful would be if two different objects have an attribute with the same name, but with different meaning. Using only hasattr might then lead to strange errors.

    One nice example is the distinction between iterators and iterables (see this question). The __iter__ methods in an iterator and an iterable have the same name but are semantically quite different! So hasattr is useless, but isinstance together with ABC's provides a clean solution.

    However, I agree that in most situations the hasattr approach (described in other answers) is the most appropriate solution.

    0 讨论(0)
  • 2020-11-22 13:06

    According to pydoc, hasattr(obj, prop) simply calls getattr(obj, prop) and catches exceptions. So, it is just as valid to wrap the attribute access with a try statement and catch AttributeError as it is to use hasattr() beforehand.

    a = SomeClass()
    try:
        return a.fake_prop
    except AttributeError:
        return default_value
    
    0 讨论(0)
  • 2020-11-22 13:07

    As Jarret Hardie answered, hasattr will do the trick. I would like to add, though, that many in the Python community recommend a strategy of "easier to ask for forgiveness than permission" (EAFP) rather than "look before you leap" (LBYL). See these references:

    EAFP vs LBYL (was Re: A little disappointed so far)
    EAFP vs. LBYL @Code Like a Pythonista: Idiomatic Python

    ie:

    try:
        doStuff(a.property)
    except AttributeError:
        otherStuff()
    

    ... is preferred to:

    if hasattr(a, 'property'):
        doStuff(a.property)
    else:
        otherStuff()
    
    0 讨论(0)
  • 2020-11-22 13:11

    This is super simple, just use dir(object)
    This will return a list of every available function and attribute of the object.

    0 讨论(0)
  • 2020-11-22 13:13

    I would like to suggest avoid this:

    try:
        doStuff(a.property)
    except AttributeError:
        otherStuff()
    

    The user @jpalecek mentioned it: If an AttributeError occurs inside doStuff(), you are lost.

    Maybe this approach is better:

    try:
        val = a.property
    except AttributeError:
        otherStuff()
    else:
        doStuff(val)
    
    0 讨论(0)
  • 2020-11-22 13:14

    You can use hasattr() or catch AttributeError, but if you really just want the value of the attribute with a default if it isn't there, the best option is just to use getattr():

    getattr(a, 'property', 'default value')
    
    0 讨论(0)
提交回复
热议问题