Table of contents
1.
Introduction
2.
What is Attribute Error in Python?
3.
Causes of Attribute Error
4.
Examples
4.1.
Example 1
4.1.1.
Code
4.1.2.
Output
4.1.3.
Explanation
4.2.
Example 2
4.2.1.
Code
4.2.2.
Output
4.2.3.
Explanation
4.3.
Example 3
4.3.1.
Code
4.3.2.
Output
4.3.3.
Explanation
5.
How to deal with Attribute Errors?
5.1.
Double-check spellings
5.2.
Use a try-except block
5.2.1.
Code
5.2.2.
Output
5.3.
Use hasattr() function
5.3.1.
Code
5.3.2.
Output
5.4.
Use dir() function
5.4.1.
Code
5.4.2.
Output
6.
Frequently Asked Questions
6.1.
What is the difference between instance attributes and class attributes?
6.2.
How to delete an attribute from an object?
6.3.
How to handle multiple exceptions in Python?
6.4.
What are runtime errors in Python?
6.5.
Can we customise the error message for an Attribute Error?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Attribute Error Python

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hey, Ninjas! As you know, we create software, online applications, and games using programming languages. Coding mistakes and errors are frequent, which is why programmes frequently crash. There are numerous kinds of errors in Python as well. An attribute error is one of the most frequent errors. 

Introduction

This article will discuss Attribute Error, its causes, examples, and how to deal with it.

What is Attribute Error in Python?

Every value in Python is an object, and every object has attributes. A class or a data type's attributes are its methods or variables. Lists, for instance, have attributes such as append()sort(), etc. Even an empty object, a class instance without any methods or variables, inherits various standard attributes from the object class, including __init__, __repr__, and others.

When we attempt to access an attribute of an object that does not exist, we face an attribute error. 

Causes of Attribute Error

The leading cause of attribute error is trying to access or assign an attribute that does not exist for the given object, which can happen due to several reasons, such as

  • Typing/spelling mistakes in the attribute name
     
  • Forgetting to define an attribute in a class
     
  • Indentation errors
     
  • Trying to access a private attribute from outside the class

Examples

Let's look at some examples of Attribute Errors in Python to understand it better.

Example 1

Let us look at the code for the first example.

Code

class MyClass:
    def __init__(self):
        self.first = 10

obj = MyClass()
print(obj.first)
print(obj.second)
You can also try this code with Online Python Compiler
Run Code

Output

Output - Example 1

Explanation

In this code, AttributeError occurs because we are trying to access the variable second, which we did not define in MyClass.

Example 2

Let us look at the code for the second example.

Code

first = 1024
print(first.bit_count())

second = "CodingNinjas"
print(second.bit_count())
You can also try this code with Online Python Compiler
Run Code

Output

Output - Example 2

Explanation

In this code, AttributeError occurs because we are trying to access the function bit_count. The int class in Python has the bit_count method, but the str class does not have the bit_count method.

Example 3

Let us look at the code for the third example.

Code

class MyClass:
    def __init__(self):
        self.__private_attribute = 100

obj = MyClass()
print(obj.__private_attribute)
You can also try this code with Online Python Compiler
Run Code

Output

Output - Example 3

Explanation

The above code raises an AttributeError because __private_attribute is private, and we cannot access it outside the class.

In Python, any attribute or method that starts with two underscores __ is considered a private attribute or method, and we cannot access them from outside the class. When we mark an attribute as private, the Python interpreter changes its name to include the class name in the attribute name, which is called name mangling. Thus, in the above code, the interpreter changes __private_attribute to _MyClass__private_attribute.

How to deal with Attribute Errors?

There are various ways to deal with attribute errors in Python. Let us look at some of them.

Double-check spellings

To avoid attribute errors in Python, we should double-check spellings and ensure we are not using undefined attributes anywhere.

Use a try-except block

Another way to deal with attribute errors is to use a try-except block. This way program does not crash even after failing. Let’s see an example of using the try-except block to understand its syntax.

Code

class MyClass:
    def __init__(self):
        self.a = 100

obj = MyClass()

try:
    print("a:", obj.a)
except AttributeError:
    print("a: Attribute Not Found!")

try:
    print("b:", obj.b)
except AttributeError:
    print("b: Attribute Not Found!")
You can also try this code with Online Python Compiler
Run Code

Output

Output of try-except block

Use hasattr() function

Before accessing, we can check if an object has a specific attribute or method using the hasattr() function. As a string, the hasattr() function takes two arguments, the object and the attribute name. It returns True if the attribute exists and False otherwise. This way, we can avoid AttributeErrorLet’s see an example of using the hasattr() function to understand its syntax.

Code

class MyClass:
    def __init__(self):
        self.a = 100

obj = MyClass()

if hasattr(obj, 'a'):
    print("a:", obj.a)
else:
    print("a: Attribute Not Found!")

if hasattr(obj, 'b'):
    print("b:", obj.b)
else:
    print("b: Attribute Not Found!")
You can also try this code with Online Python Compiler
Run Code

Output

Output of hasattr() function

Use dir() function

Before accessing, we can check if an object has a particular attribute or method using the dir() function. The dir() function returns a list of all attributes of an object. Using the in operator, we can check if a specific attribute is in this list. This way, we can avoid AttributeError. Let’s see an example of using the dir() function to understand its syntax.

Code

class MyClass:
    def __init__(self):
        self.a = 100

obj = MyClass()

if 'a' in dir(obj):
    print("a:", obj.a)
else:
    print("a: Attribute Not Found!")

if 'b' in dir(obj):
    print("b:", obj.b)
else:
    print("b: Attribute Not Found!")
You can also try this code with Online Python Compiler
Run Code

Output

Output of dir() function

Also see,  Convert String to List Python

Frequently Asked Questions

What is the difference between instance attributes and class attributes?

An instance attribute is an attribute that belongs to a specific instance of a class. A class attribute is an attribute that belongs to the class itself, meaning all instances of that class share it.

How to delete an attribute from an object?

We can delete an attribute from an object using the del keyword. For example, del obj.a deletes attribute a from object obj.

How to handle multiple exceptions in Python?

We use multiple except statements in one try-except block to handle multiple exceptions. Another way to manage multiple exceptions is using a tuple of exceptions in the except statement.

What are runtime errors in Python?

Runtime errors in Python are errors that happen when the program is running. They are also called exceptions, and we can handle them using try and except blocks in Python. Some examples include NameError, TypeError, KeyError, AttributeError, etc.

Can we customise the error message for an Attribute Error?

We can customise the error message for AttributeError in Python by using a try/except block and raising a custom exception with a custom message.

Conclusion

This article explores how to deal with Attribute Errors in Python, their causes and ways to handle them. We have seen that Attribute Errors occur when we try to access an attribute that does not exist in an object. By understanding the causes of attribute errors and ways to handle them, we can now write more robust and error-free code.

We recommend reading the following articles to learn more about Python:

If you liked our article, do upvote our article and help other ninjas grow. You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

Happy Coding!

Live masterclass