Python AttributeError: A Complete Guide

Posted in /  

Python AttributeError: A Complete Guide

Vinay Khatri
Last updated on June 10, 2022

    Attributes are the properties and methods defined for a class, object or data type. In Python, everything is an object, that's why many inbuilt data types such as list, tuple, int, float, etc support methods and properties. Different objects have different attribute values, for instance, list support append() method whereas the tuple does not. And if we try to call the append() method on a tuple object we will receive the AttributeError with an error message that this tuple object does not have the following attribute. This is not only with tuple and list, every object whether it is an object of a user-defined class or an inbuilt data type, if we try to access an unsupported attribute(property or method) on that object we will encounter the AttributeError. In this Python tutorial, we will discuss what is AttributeError and why it occurs in a Python program.

    What is  Python AttributeError?

    AttributeError is one of Python's standard exceptions. And as a Python developer, you will encounter this error many times. But once you know why this error is raised in your program you would be able to solve it in no time. Before we discuss the AttributeError let's take a look at what is an attribute? What are Attributes? Attributes are the properties and the methods that are defined for a class or object. When we create a class using the class keywords, all the properties and methods defined inside that class will be called the class attributes. And once we define an object for that class we can access those attributes using that object only. Similarly, the built-in objects like list, tuple, dictionary, int, float etc. come with built-in attributes. We can list out all the supported attributes of an object using the dir() function. Example

    # all inbuilt attributes of list objects
    
    x = [1,3,5,7,9]
    
    print("List attributes")
    print(dir(x))
    

    Output

    List attributes
    ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', 
    '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', 
    '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', 
    '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
    '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__',
     '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 
    'remove', 'reverse', 'sort'
    ]

    AttributeError

    To access an attribute of an object we use the object name followed by the dot operator and the attribute name. If the attribute is a method we also put the parenthesis " () " after the attribute name. But if we try to access such an attribute that does not exist for that object then we will receive the attribute Error.

    Example 1 AttributeError with built-in Objects

    Let's say we have two containers container1 is a list object and container2 is a set object. We also have a string which words we need to add into these two containers. As container1 is a list it can contain duplicate words but the container2 will only contain unique words.

    string = "As the years pass by, we all know owners look more and more like their dogs"
    
    #list container
    container1 = list()
    
    #set container
    container2 = set()
    
    for word in string.split():
        container1.append(word)    #add word to the list
        container2.append(word)    #add word to the set (error)
    
    print("List container: ", container1)
    print("Set container: ", container2)
    

    Output

    Traceback (most recent call last):
      File "main.py", line 11, in 
        container2.append(word)    #add word to the set (error)
    AttributeError: 'set' object has no attribute 'append'

    In this example, we are getting the attribute error "AttributeError: 'set' object has no attribute 'append'" . This is because container2 is a set object and it does not have any method append() . append() method is only supported by Python's list objects. To add a new element to the set object we use add() method. Example 1 solution

    string = "As the years pass by, we all know owners look more and more like their dogs"
    
    #list container
    container1 = list()
    
    #set container
    container2 = set()
    
    for word in string.split():
        container1.append(word)    #add word to the list
        container2.add(word)    #add word to the set 
    
    print("List container: ", container1)
    print("Set container: ", container2)
    

    Output

    List container: ['As', 'the', 'years', 'pass', 'by,', 'we', 'all', 'know', 'owners', 'look', 'more', 'and', 'more', 'like', 'their', 'dogs']
    Set container: {'pass', 'like', 'the', 'we', 'know', 'years', 'and', 'by,', 'their', 'dogs', 'look', 'owners', 'As', 'all', 'more'}

    Example 2 AttributeError class and objects

    We also the attribute error when we try to access such property or method of a class that does not exist. This generally happens when we make some typos while calling a property or method.

    class Order:
        def __init__(self, product, name):
            self.product = product
            self.name = name
    
        def price(self):
            if self.product == "coffee":
                return 200
            if self.product == "tea":
                return 100
    
    order1 = Order("coffee", "Raj")
    
    print("Bill: ", order1.bill())
    

    Output

    Traceback (most recent call last):
      File "main.py", line 14, in 
        print("Bill: ", order1.bill())
    AttributeError: 'Order' object has no attribute 'bill'

    In the above example, we are getting this error because we are trying to access the bill() method that is not defined in the Order class. To solve this problem we need to ensure that we are calling the correct method, to access the price for our product. In our Order class to get the total price we have price() method not bill() . Example 2 solution

    class Order:
        def __init__(self, product, name):
            self.product = product
            self.name = name
    
        def price(self):
            if self.product == "coffee":
                return 200
            if self.product == "tea":
                return 100
    
    order1 = Order("coffee", "Raj")
    
    print("Bill: ", order1.price())
    

    Output

    Bill: 200

    Conclusion

    Attribute Error is raised in a Python program when we try to access an unsupported attribute using an object. To solve the error we need to ensure that the method or property we are trying to access through the object, does support by the object. If you are getting this error with some built-in data type object and do not know all the attributes of the object. For that, you can use the Python dir() function, and it will list out all the attributes supported by that particular object. People are also reading:

    Leave a Comment on this Post

    0 Comments