How to Fix AttributeError in Python

Before we look into what AttributeError, we try and understand what an Attribute reference is in Python.


What is an Attribute Reference in Python

    In Python an attribute reference is a primary followed by a period and a identifier.

    attributeref ::=  primary "." identifier

    The primary is usually of type object.

    Using this object an attribute is produced with the help of an identifier.

    If the identifier results in no attribute then an exception AttributeError is raised.

    Let's take a look at it with a very simple example.


    Example:
    name = "Sam"
    name.something
    Output:
    Traceback (most recent call last):
      File "/Users/c2ctechtv/Desktop/example.py", line 2, in <module>
        name.something
    AttributeError: 'str' object has no attribute 'something'
    Python AttributeError- str object has no attribute something

    As you can see, we created an object of type Str and then on the next line, make use of an identifier that does not exist, thus this resulted in AttributeError.

    So the fix is to make sure that the object does support attribute references.


Reference:

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!