- Why does AttributeError Occur in Python?
- How to fix AttributeError: object has no attribute in Python class
- 1. The method or attribute doesn’t exist in the class
- 2. The method or attribute isn’t a member of the class
- Take your skills to the next level ⚡️
- About
- Search
- Tags
- Python AttributeError: Why It Happens and How You Can Fix It
- How Do You Check Which Attributes Exist in a Python Object?
- Attribute Error Tutorial Wrap Up
- How to Fix AttributeError in Python
- What Causes AttributeError
- Python AttributeError Example
- How to Fix AttributeError in Python
- Track, Analyze and Manage Errors With Rollbar
Why does AttributeError Occur in Python?
Attribute error occurs in python when we try to assign an attribute value to a python objects or class instance in which that particular attribute does not exist. In other word when the python compiler not able to find defined data or attribute on an object which allow for attribute references, it throws the «AttributeError».
Error Code Example:
welcome = "Hello World <>".formats("Stechies") print(welcome)
Traceback (most recent call last): File "t.py", line 1, in welcome = "Hello World <>".formats("Stechies") AttributeError: 'str' object has no attribute 'formats'
We are getting this error because we have assigned format() functions as formats(). While compiling the code python compiler search for the specific format of function and throws the ‘Attribute Error’.
Correct Code:
welcome = "Hello World <>".format("Stechies") print(welcome)
Error Code 2:
str = " STechies " print("String with Strip: " + str.sstrip())
Traceback (most recent call last): File "t.py", line 7, in print("String with Strip: " + str.sstrip()) AttributeError: 'str' object has no attribute 'sstrip'
In the above example we have assigned strip() function as sstrip() which causes the error.
Explanation:
This type of error occur when we try to join two different function, method or objects with DOT operator (.) or miss-spell.
Correction for Error Code 2:
str = " STechies " print("String with Strip: " + str.strip())
String with Strip: STechies
How to fix AttributeError: object has no attribute in Python class
One error that you might encounter when working with Python classes is:
- The method or attribute doesn’t exist in the class.
- The method or attribute isn’t a member of the class.
The following tutorial shows how to fix this error in both cases.
1. The method or attribute doesn’t exist in the class
Let’s say you code a class named Human with the following definitions:
Next, you created an object from this class and called the eat() method:
You receive an error because the eat() method is not defined in the class:
To fix this you need to define the eat() method inside the class as follows:
Now Python can run the eat() method and you won’t receive the error.
The same goes for attributes you want the class to have. Suppose you want to get the age attribute from the person object:
The call to person.age as shown above will cause an error because the Human class doesn’t have the age attribute.
You need to add the attribute into the class:
With the attribute defined inside the class, you resolved this error.
2. The method or attribute isn’t a member of the class
Suppose you have a class with the following indentations in Python:
Next, you created a Human object and call the walk() method as follows:
You’ll receive an error as follows:
This error occurs because the walk() method is defined outside of the Human class block.
How do I know? Because you didn’t add any indent before defining the walk() method.
In Python, indentations matter because they indicate a block of code, like curly brackets <> in Java or JavaScript.
When you write a member of the class, you need to indent each line according to the class structure you want to create.
The indentations must be consistent, meaning if you use a space, each indent must be a space. The following example uses one space for indentations:
This one uses two spaces for indentations:
And this uses four spaces for indentations:
When you incorrectly indent a function, as in not giving any indent to the walk() method, then that method is defined outside of the class:
You need to appropriately indent the method to make it a member of the class. The same goes when you’re defining attributes for the class:
You need to pay careful attention to the indentations in your code to fix the error.
I hope this tutorial is helpful. Have fun coding! 😉
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with:
Python AttributeError: Why It Happens and How You Can Fix It
Have you seen the Python AttributeError while writing your program and don’t know how to fix it? This tutorial will give the answer to that.
If you are getting started with Python you might have experience seeing lots of different Python errors. The Python AttributeError is a very common type of error.
The Python AttributeError is a type of exception raised when your Python program tries to access an attribute that doesn’t exist on a variable/object. The description of the attribute error tells you the specific line of code, type of the variable, and attribute causing the error. Sometimes the error message also suggests a potential fix.
Right now you might not know what to do with this error if you are new to the Python programming language.
After going through this tutorial you will know how to fix the AttributeError in your Python code.
Let’s learn more about the AttributeError in Python!
Let’s update our code and use the upper() method instead of to_upper().
message = "Let's cause an attribute error in Python" print(message.upper()) [output] LET'S CAUSE AN ATTRIBUTE ERROR IN PYTHON
The output is now correct and the initial message has been converted to uppercase.
How Do You Check Which Attributes Exist in a Python Object?
We have seen that you can use your IDE or Python’s official documentation to identify the correct attributes to use in your Python programs when working with a variable (or any Python object).
There is a quick way to identify all the attributes provided by a variable in your Python program. You can use Python’s dir() built-in function. Call this function and pass the variable to it. As a result, you will get the list of attributes available for that variable.
To see how this works, open the Python shell, create a string, and call the dir() function by passing the string variable to it.
>>> message = "test message" >>> dir(message) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
From the output of the dir() function you can also see the upper() method we have used previously in this tutorial to fix the AttributeError.
Attribute Error Tutorial Wrap Up
In this Python tutorial, we have seen what to do when the execution of your program fails due to an AttributeError.
- why this error/exception occurs: you are calling an attribute that is not supported by the variable/object you are calling it against.
- where to find more details about the AttributeError: the Python traceback tells you the line of code causing the error, the variable type, and the attribute called.
- how to fix the AttributeError: use your IDE, the dir() built-in function, or the official Python documentation to identify the correct attribute (method) to use.
Well done! Now you can fix the error you are seeing in your program and move forward with the development!
Related article: one of the things we have done in this tutorial is working with a Python string. Do you want to learn more about strings? Here is another Codefather tutorial that shows how to concatenate strings in Python.
I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!
How to Fix AttributeError in Python
The Python AttributeError is an exception that occurs when an attribute reference or assignment fails. This can occur when an attempt is made to reference an attribute on a value that does not support the attribute.
What Causes AttributeError
The Python AttributeError is raised when an invalid attribute reference is made. This can happen if an attribute or function not associated with a data type is referenced on it. For example, if a method is called on an integer value, an AttributeError is raised.
Python AttributeError Example
Here’s an example of a Python AttributeError raised when trying call a method on an integer:
In the above example, a method is attempted to be called on an integer. Since integers in Python do not support any methods, running the above code raises a AttributeError :
Traceback (most recent call last): File "test.py", line 2, in i.append(2) AttributeError: 'int' object has no attribute 'append'
How to Fix AttributeError in Python
To avoid the AttributeError in Python code, a check should be performed before referencing an attribute on an object to ensure that it exists. The Python help() function can be used to find out all attributes and methods related to the object.
To resolve the AttributeError , a try-except block can be used. The lines of code that can throw the AttributeError should be placed in the try block, and the except block can catch and handle the error.
Using the above approach, the previous example can be updated to handle the error:
i = 1 try: i.append(2) except AttributeError: print('No such attribute')>
Here, a check is performed for the AttributeError using the try-except block. When the above code is executed, the except block catches the AttributeError and handles it, producing the following output:
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!