Object has no attribute python ошибка

One error that you might encounter when working with Python classes is:

AttributeError: 'X' object has no attribute 'Y'

This error usually occurs when you call a method or an attribute of an object. There are two possible reasons for this error:

  1. The method or attribute doesn’t exist in the class.
  2. 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:

class Human:
    def __init__(self, name):
        self.name = name
    def walk(self):
        print("Walking")

Next, you created an object from this class and called the eat() method:

person = Human("John")

person.eat()

You receive an error because the eat() method is not defined in the class:

Traceback (most recent call last):
  File "main.py", line 10, in <module>
    person.eat()
AttributeError: 'Human' object has no attribute 'eat'

To fix this you need to define the eat() method inside the class as follows:

class Human:
    def __init__(self, name):
        self.name = name
    def walk(self):
        print("Walking")
    def eat(self):
        print("Eating")

person = Human("John")

person.eat()  # Eating

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:

person = Human("John")

print(person.age)  # ❌

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:

class Human:
    age = 22
    def __init__(self, name):
        self.name = name
    def walk(self):
        print("Walking")

person = Human("John")

print(person.age)  # 22

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:

class Human:
    def __init__(self, name):
        self.name = name
def walk():
    print("Walking")

Next, you created a Human object and call the walk() method as follows:

person = Human("John")

person.walk() # ❌

You’ll receive an error as follows:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    person.walk()
AttributeError: 'Human' object has no attribute 'walk'

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:

class Human:
 def __init__(self, name):
  self.name = name
 def walk(self):
  print("Walking")

This one uses two spaces for indentations:

class Human:
  def __init__(self, name):
    self.name = name
  def walk(self):
    print("Walking")

And this uses four spaces for indentations:

class Human:
    def __init__(self, name):
        self.name = name
    def walk(self):
        print("Walking")

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:

class Human:
    def __init__(self, name):
        self.name = name
def walk():
    print("Walking")

# Valid
walk()  # ✅

# Invalid
person = Human("John")
person.walk()  # ❌

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:

class Human:
    age = 22
    def __init__(self, name):
        self.name = name
    def walk(self):
        print("Walking")

# Valid
person = Human("John")
person.walk()  # ✅
print(person.age)  # ✅

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! 😉

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!

What Is a Python AttributeError?

A Python AttributeError occurs when you try to use an attribute on a variable of a type that doesn’t support that attribute. For example, you try to call a method on a string and that method is not supported by the string data type. A method represents a functionality provided by a given Python data type or object (e.g. a string, int, boolean).

And is there a generic approach to troubleshooting and fixing a Python AttributeError?

To fix a Python AttributeError in your program you have to identify the variable causing the error. The traceback of the error helps you identify the root cause of this type of error because it includes the line of code where the error occurs. The traceback also tells you the name of the invalid attribute used in your program.

To make this simple, a Python AttributeError occurs when:

  • You call an attribute of a variable (using the dot notation).
  • That attribute does not exist on that variable/object.

Let’s go through two examples that will show you why the AttributeError is raised and the steps you can take to fix it.

How to Fix AttributeError in Python: ‘int’ object has no attribute

Let’s see an example of an attribute error when working with an integer in Python.

We will create an integer variable and then try to sum another integer to it using an attribute not supported by the int data type.

number = 5
total = number.add(4)
print("The total is", total)

Try to execute this code, you will see the following AttributeError exception:

Traceback (most recent call last):
  File "/opt/codefather/tutorials/attribute_error.py", line 2, in <module>
    total = number.add(4)
AttributeError: 'int' object has no attribute 'add'

The attribute error says that an “int” object (in other words an integer) has not attribute “add”. This means that the .add() method (a method is a type of function) is not provided by an integer in Python.

The traceback is telling you that:

  • The error occurred on line 2 of the code (it even shows you the content of that line).
  • This is caused by the attribute “add” called on an “int” variable (object).

With these two pieces of information, you can immediately see that the variable to focus on is number and the code causing the error is number.add(4).

So, how can we fix this error?

Simply remove .add(4) and use the plus sign to calculate the sum of the two numbers. We will be using the plus operator that is supported by a variable of type integer.

Here is the correct code:

number = 5
total = number + 4
print("The total is", total)

[output]
The total is 9

You can see that this time there is no attribute error and the result is correct.

How to Fix AttributeError in Python: ‘str’ object has no attribute

Let’s have a look at another example of AttributeError raised with a Python string.

Imagine you want to convert every single character in a message (string data type) to upper case. You know that there is a way to do it in Python but you don’t remember exactly how.

So you try to use the dot notation followed by to_upper().

message = "Let's cause an attribute error in Python"
print(message.to_upper())

Here is the error you get.

Traceback (most recent call last):
  File "/opt/codefather/tutorials/tempCodeRunnerFile.py", line 2, in <module>
    print(message.to_upper())
AttributeError: 'str' object has no attribute 'to_upper'. Did you mean: 'isupper'?

The Python interpreter raises an AttributeError because a “str” object (in other words, a string) doesn’t have the attribute “to_upper”. Python is also suggesting that maybe we wanted to use “isupper” instead.

The error is also telling you that the line of code causing this error is line 2 and it shows you the code causing the error: “print(message.to_upper())”.

To fix this error you have to replace the method “to_upper()” with the correct method a Python string provides to convert a string to upper case.

How can you find the correct method?

One way is by typing the dot ( . ) after the variable name and by looking for the correct method in the list of methods suggested by your IDE (e.g. Visual Studio Code or PyCharm).

Another option is to look at the official Python documentation for string methods. If you don’t know what to look for you might be searching for “to uppercase” on that page. This will get you to the “str.upper()” section of that page.

Use str.upper() to fix Python AttributeError

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.

Now you know:

  • 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.

Claudio Sabato - Codefather - Software Engineer and Programming Coach

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

I have a class MyThread. In that, I have a method sample. I am trying to run it from within the same object context. Please have a look at the code:

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter, redisOpsObj):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
        self.redisOpsObj = redisOpsObj
        
    def stop(self):
        self.kill_received = True
            
    def sample(self):
        print "Hello"
                
    def run(self):
        time.sleep(0.1)
        print "\n Starting " + self.name
        self.sample()

Looks very simple ain’t it. But when I run it I get this error

AttributeError: 'myThread' object has no attribute 'sample' Now I have that method, right there. So what’s wrong? Please help

Edit: This is the stack trace

Starting Thread-0

Starting Thread-1
Exception in thread Thread-0:
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner
self.run()
File "./redisQueueProcessor.py", line 51, in run
self.sample()
AttributeError: 'myThread' object has no attribute 'sample'

Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner
self.run()
File "./redisQueueProcessor.py", line 51, in run
self.sample()
AttributeError: 'myThread' object has no attribute 'sample'

I am calling it like this

arThreads = []
maxThreads = 2;

for i in range( maxThreads ):
    redisOpsObj = redisOps()
    arThreads.append( myThread(i, "Thread-"+str(i), 10, redisOpsObj) )

Sorry, I can’t post the redisOps class code. But I can assure you that it works just fine

Fix Object Has No Attribute Error in Python

Attributes are functions or properties associated with an object of a class. Everything in Python is an object, and all these objects have a class with some attributes. We can access such properties using the . operator.

This tutorial will discuss the object has no attribute python error in Python. This error belongs to the AttributeError type.

We encounter this error when trying to access an object’s unavailable attribute. For example, the NumPy arrays in Python have an attribute called size that returns the size of the array. However, this is not present with lists, so if we use this attribute with a list, we will get this AttributeError.

See the code below.

import numpy as np

arr1 = np.array([8,4,3])
lst = [8,4,3]

print(arr1.size)
print(lst.size)

Output:

3
AttributeError: 'list' object has no attribute 'size'

The code above returns the size of the NumPy array, but it doesn’t work with lists and returns the AttributeError.

Here is another example with user-defined classes.

class A:
    def show():
        print("Class A attribute only")
        
class B:
    def disp():
        print("Class B attribute only")
        
a = A()
b = B()
b.show()

Output:

AttributeError: 'B' object has no attribute 'show'

In the example above, two classes were initiated with similar functions to display messages. The error shows because the function called is not associated with the B class.

We can tackle this error in different ways. The dir() function can be used to view all the associated attributes of an object. However, this method may miss attributes inherited via a metaclass.

We can also update our object to the type that supports the required attribute. However, this is not a good method and may lead to other unwanted errors.

We can also use the hasattr() function. This function returns True if an attribute belongs to the given object. Otherwise, it will return False.

See the code below.

class A:
    def show():
        print("Class A attribute only")
        
class B:
    def disp():
        print("Class B attribute only")
        
a = A()
b = B()
lst = [5,6,3]
print(hasattr(b, 'disp'))
print(hasattr(lst, 'size'))

Output:

In the example above, object b has the attribute disp, so the hasattr() function returns True. The list doesn’t have an attribute size, so it returns False.

If we want an attribute to return a default value, we can use the setattr() function. This function is used to create any missing attribute with the given value.

See this example.

class B:
    def disp():
        print("Class B attribute only")

b = B()
setattr(b, 'show', 58)
print(b.show)

Output:

The code above attaches an attribute called show with the object b with a value of 58.

We can also have a code where we are unsure about the associated attributes in a try and except block to avoid any error.

In every programming language, if we develop new programs, there is a high chance of getting errors or exceptions. These errors yield to the program not being executed. One of the error in Python mostly occurs is “AttributeError”. AttributeError can be defined as an error that is raised when an attribute reference or assignment fails. 
For example, if we take a variable x we are assigned a value of 10. In this process suppose we want to append another value to that variable. It’s not possible. Because the variable is an integer type it does not support the append method. So in this type of problem, we get an error called “AttributeError”. Suppose if the variable is list type then it supports the append method. Then there is no problem and not getting”Attribute error”.

Note: Attribute errors in Python are generally raised when an invalid attribute reference is made.
There are a few chances of getting AttributeError.
Example 1:

Python3

Output:

Traceback (most recent call last):
  File "/home/46576cfdd7cb1db75480a8653e2115cc.py", line 5, in 
    X.append(6)
AttributeError: 'int' object has no attribute 'append'

Example 2: Sometimes any variation in spelling will cause an Attribute error as Python is a case-sensitive language.

Python3

string = "The famous website is { }".fst("geeksforgeeks")

print(string)

Output:

Traceback (most recent call last):
  File "/home/2078367df38257e2ec3aead22841c153.py", line 3, in 
    string = "The famous website is { }".fst("geeksforgeeks")
AttributeError: 'str' object has no attribute 'fst'

Example 3: AttributeError can also be raised for a user-defined class when the user tries to make an invalid attribute reference.

Python3

class Geeks():

    def __init__(self):

        self.a = 'GeeksforGeeks'

obj = Geeks()

print(obj.a)

print(obj.b)

Output: 

GeeksforGeeks

Error:

Traceback (most recent call last):
  File "/home/373989a62f52a8b91cb2d3300f411083.py", line 17, in 
    print(obj.b)
AttributeError: 'Geeks' object has no attribute 'b'

Example 4:  AttributeError can also be raised for a user-defined class when the user misses out on adding tabs or spaces between their lines of code.

Python3

class dict_parsing:

    def __init__(self,a):

        self.a = a

        def getkeys(self):

            if self.notdict():

                return list(self.a.keys())

        def getvalues(self):

            if self.notdict():

                return list(self.a.values())

        def notdict(self):

            if type(self.a) != dict:

                raise Exception(self,a,'not a dictionary')

            return 1

        def userinput(self):

            self.a = eval(input())

            print(self.a,type(self.a))

            print(self.getykeys())

            print(self.getvalyes())

        def insertion(self,k,v):

            self.a[k]=v

d = dict_parsing({"k1":"amit", "k2":[1,2,3,4,5]})

d.getkeys()

Output:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-9-c26cd169473f> in <module>
----> 1 d.getkeys()

AttributeError: 'dict_parsing' object has no attribute 'getkeys'

Error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-9-c26cd169473f> in <module>
----> 1 d.getkeys()
AttributeError: 'dict_parsing' object has no attribute 'getkeys'

Solution for AttributeError

Errors and exceptions in Python can be handled using exception handling i.e. by using try and except in Python. 
 

Example: Consider the above class example, we want to do something else rather than printing the traceback Whenever an AttributeError is raised.

Python3

class Geeks():

    def __init__(self):

        self.a = 'GeeksforGeeks'

obj = Geeks()

try:

    print(obj.a)

    print(obj.b)

except AttributeError:

    print("There is no such attribute")

Output:

GeeksforGeeks
There is no such attribute

Note: To know more about exception handling click here.

Last Updated :
03 Jan, 2023

Like Article

Save Article

Понравилась статья? Поделить с друзьями:
  • Object finereader ошибка цб
  • Obd ошибки что это
  • Obd2 как сбросить ошибки на
  • Obd2 can коды ошибок
  • Obd1 ошибки chevrolet