Attributeerror python как исправить

Автор оригинала: Team Python Pool.

Ошибки – неотъемлемая часть жизни программиста. И это совсем не плохо, если вы получаете ошибку. Получение ошибки означает, что вы изучаете что-то новое. Но мы должны устранить эти ошибки. И прежде чем решить эту ошибку, мы должны знать, почему мы получаем эту ошибку. В python есть некоторые часто встречающиеся ошибки, такие как Ошибка типа , Синтаксическая ошибка, Ошибка ключа, Ошибка атрибута, Ошибка имени, и так далее.

В этой статье мы узнаем о том, что такое python AttributeError, почему мы его получаем и как его разрешаем? Интерпретатор Python вызывает AttributeError, когда мы пытаемся вызвать или получить доступ к атрибуту объекта, но этот объект не обладает этим атрибутом. Например, Если мы попытаемся использовать функцию upper() для целого числа, то получим ошибку атрибута.

Почему мы Получаем AttributeError?

Всякий раз, когда мы пытаемся получить доступ к атрибуту, который не принадлежит этому объекту, мы получаем attributeerror. Например, Мы знаем, что для того, чтобы сделать строку прописной, мы используем upper().

Выход-

AttributeError: 'int' object has no attribute 'upper'

Здесь мы пытаемся преобразовать целое число в заглавную букву, что невозможно, поскольку целые числа не приписывают быть верхними или нижними. Но если попытаться использовать эту функцию upper() для строки, мы получим результат, потому что строка может быть квалифицирована как верхняя или нижняя.

Если мы попытаемся выполнить append() для любого типа данных, отличного от List:

Иногда, когда мы хотим объединить две строки, мы пытаемся добавить одну строку в другую, что невозможно, и мы получаем ошибку атрибута.

Выход-

AttributeError: 'str' object has no attribute 'append'

То же самое относится и к кортежам,

Выход-

AttributeError: 'tuple' object has no attribute 'append'

Попытка доступа к атрибуту класса:

Иногда мы пытаемся получить доступ к атрибутам класса, которыми он не обладает. Давайте лучше разберемся в этом на примере.

Здесь у нас есть два класса – один-класс человека, а другой – класс транспортного средства. Оба обладают разными свойствами.

class Person: 

   def __init__(self,age,gender,name): 
       
       
       

   def speak(self): 
        print("Hello!! How are you?") 

class Vehicle: 

   def __init__(self , model_type , engine_type): 
        
        

   def horn(self): 
        print("beep!! beep") 
(20,"male","ashwini") 
print(ashwini.gender) 
print(ashwini.engine_type)

Выход-

male  
AttributeError: 'Person' object has no attribute 'engine_type'
AttributeError: 'Person' object has no attribute 'horn'

Выход-

Petrol 
AttributeError: 'Vehicle' object has no attribute 'gender'
Error-
AttributeError: 'Vehicle' object has no attribute 'speak'

В приведенных выше примерах, когда мы попытались получить доступ к свойству пола класса Person, нам это удалось. Но когда мы попытались получить доступ к атрибуту engine_type (), он показал нам ошибку. Это происходит потому, что у человека нет атрибута под названием engine_type. Точно так же, когда мы попытались вызвать engine_type на транспортном средстве, мы добились успеха, но это было не в случае пола, так как Транспортное средство не имеет атрибута, называемого полом.

AttributeError: ‘NoneType’

Мы получаем ошибку NoneType, когда получаем “None” вместо экземпляра, который, как мы предполагаем, мы получим. Это означает, что задание провалилось или вернуло неожиданный результат.

Выход-

AttributeError: 'NoneType' object has no attribute 'upper'

При работе с модулями:

Очень часто при работе с модулями возникает ошибка атрибута. Предположим, мы импортируем модуль с именем hello и пытаемся получить доступ к двум функциям в нем. Один из них-print_name (), а другой-print_age().

Модуль Привет-

def print_name():
    print("Hello! The name of this module is module1")

import hello

hello.print_name()
hello.print_age()

Выход-

Hello! The name of this module is module1

AttributeError: module 'hello' has no attribute 'print_age'

Поскольку модуль hello не содержит атрибута print_age, мы получили атрибут Attributeerror. В следующем разделе мы узнаем, как устранить эту ошибку.

Как разрешить AttributeError в Python

Используйте справку():

Разработчики python пытались решить любую возможную проблему, с которой сталкиваются программисты Python. В этом случае также, если мы путаемся в том, принадлежит ли конкретный атрибут объекту или нет, мы можем использовать help(). Например, если мы не знаем, можем ли мы использовать append() для строки, мы можем print(help(str)) знать все операции, которые мы можем выполнять со строками. Не только эти встроенные типы данных, но мы также можем использовать help() для пользовательских типов данных, таких как Class.

Например, если мы не знаем, какими атрибутами обладает класс Person, объявленный нами выше,

Выход-

ошибка атрибута pythonошибка атрибута python

Разве это не здорово! Это именно те атрибуты, которые мы определили в нашем классе Персон.

Теперь давайте попробуем использовать help() для нашего модуля hello внутри модуля hi.

Help on module hello:
NAME
hello
FUNCTIONS
print_name()

Использование оператора Try – Except

Очень <сильный>профессиональный способ справиться не только с атрибутивной ошибкой, но и с любой ошибкой-это использовать try-except операторы. Если мы думаем, что можем получить ошибку в определенном блоке кода, мы можем заключить их в href=”https://en.wikipedia.org/wiki/Exception_handling”>попробуйте заблокировать. Давайте посмотрим, как это сделать. href=”https://en.wikipedia.org/wiki/Exception_handling”>попробуйте заблокировать. Давайте посмотрим, как это сделать.

Предположим, мы не уверены, содержит ли класс Person атрибут engine_type или нет, мы можем заключить его в блок try.

class Vehicle: 

   def __init__(self , model_type , engine_type): 
        
        

   def horn(self): 
        print("beep!! beep") 
( "Hatchback" , "Petrol" ) 

try: 
   print(car.engine_type) 
   print(car.gender) 

except Exception as e: 
   print(e)

Выход-

Petrol 
'Vehicle' object has no attribute 'gender'.

Должен Читать

  • Как преобразовать строку в нижний регистр в
  • Как вычислить Квадратный корень
  • Пользовательский ввод | Функция ввода () | Ввод с клавиатуры
  • Лучшая книга для изучения Python

Вывод

Всякий раз, когда мы пытаемся получить доступ к атрибуту объекта, который ему не принадлежит, мы получаем AttributeError в Python. Мы можем решить эту проблему с помощью функции help() или операторов try-except.

Попробуйте запустить программы на вашей стороне и дайте нам знать, если у вас есть какие-либо вопросы.

Счастливого кодирования!

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:

i = 1
i.append(2)

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 <module>
    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:

No such attribute

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!

blog banner for post titled: How to Solve Guide for Python AttributeError

We raise a Python AttributeError when we try to call or access an attribute of an object that does not exist for that object.

This tutorial will go through what an attribute is, what the AttributeError is in detail, and we will go through four examples to learn how to solve the error.

Table of contents

  • What is a Python AttributeError?
  • Example #1: Trying to Use append() on a String
    • Solution
  • Example #2: Trying to Access an Attribute of a Class that does not exist
    • Solution
  • Example #3: NoneType Object has no Attribute
    • Solution
  • Example #4: Handling Modules
    • Solution
  • Summary

What is a Python AttributeError?

An attribute of an object is a value or a function associated with that object. We can express calling a method of a class as referencing an attribute of a class.

Let’s look at an example of a Python class for the particle electron

class Electron:
    def __init__(self):
        self.charge = -1
        self.mass = 0.51
        self.spin = 1/2
 
    def positron(self):
        self.charge = +1
        return self.charge

We can think of an attribute in Python as a physical attribute of an object. In this example, the fundamental particle, the electron, has physical attributes of charge, mass, and spin. The Electron class has the attributes charge, mass, and spin.

An attribute can also be a function. The function positron() returns the charge of the electron’s anti-particle, the positron.

Data types can have attributes. For example, the built-in data type List has the append() method to append elements to an existing list. Therefore, List objects support the append() method. Let’s look at an example of appending to a list:

a_list = [2, 4, 6]

a_list.append(8)

print(a_list)

Attributes have to exist for a class object or a data type for you to reference it. If the attribute is not associated with a class object or data type, you will raise an AttributeError.

Example #1: Trying to Use append() on a String

Let’s look at an example scenario where we concatenate two strings by appending one string to another.

string1 = "research"

string2 = "scientist"

string1.append(string2)

Using append() is impossible because the string data type does not have the append() method. Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
1 string1.append(string2)

AttributeError: 'str' object has no attribute 'append'

Solution

To solve this problem, we need to define a third string. We can then concatenate the two strings using the + symbol and assign the result to the third string. We can concatenate a space between the two strings so that the words do not run together. Let’s look at how the revised code:

string1 = "research"

string2 = "scientist"

string3 = string1 + " " + string2

print(string3)
research scientist

Example #2: Trying to Access an Attribute of a Class that does not exist

Let’s look at an example scenario where we want to access an attribute of a class that does not exist. We can try to create an instance of the class Electron from earlier in the tutorial. Once we have the instance, we can try to use the function get_mass() to print the mass of the electron in MeV.

class Electron:

   def __init__(self):

       self.charge = -1

       self.mass = 0.51

       self.spin = 1/2
  
   def positron(self):

       self.charge = +1

       return self.charge

electron = Electron()

mass = electron.get_mass()

If we try to run the code, we get the following error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
1 mass = electron.get_mass()

AttributeError: 'Electron' object has no attribute 'get_mass'

The Electron class has no attribute called get_mass(). Therefore we raise an AttributeError.

Solution

To solve this, we can do two things. We can add the method to the class and use a try-except statement. First, let’s look at adding the method:

class Electron:
    def __init__(self):
        self.charge = -1
        self.mass = 0.51
        self.spin = 1/2

    def positron(self):
        self.charge = +1
        return self.charge

    def get_mass(self):
            return self.mass
electron = Electron()

mass = electron.get_mass()

print(f' The mass of the electron is {mass} MeV')

 The mass of the electron is 0.51 MeV

Secondly, let’s look at using try-except to catch the AttributeError. We can use try-except statements to catch any error, not just AttributeError. Suppose we want to use a method called get_charge() to get the charge of the electron object, but we are not sure whether the Electron class contains the get_charge() attribute. We can enclose the call to get_charge() in a try-except statement.

class Electron:

    def __init__(self):

        self.charge = -1

        self.mass = 0.51

        self.spin = 1/2

    def positron(self):

        self.charge = +1

        return self.charge

    def get_mass(self):

            return self.mass

electron = Electron()

try:

    charge = electron.get_charge()

except Exception as e:

    print(e)
'Electron' object has no attribute 'get_charge'

Using try-except statements aligns with professional development and makes your programs less prone to crashing.

Example #3: NoneType Object has no Attribute

NoneType means that whatever class or object you are trying to access is None. Therefore, whenever you try to do a function call or an assignment for that object, it will raise the AttributeError: ‘NoneType’ object has no attribute. Let’s look at an example scenario for a specific NoneType attribute error. We will write a program that uses regular expressions to search for an upper case “S” character at the beginning and print the word. We need to import the module re for regular expression matching.

import re

# Search for an upper case "S" character in the beginning of a word then print the word

string = "Research Scientist"

for i in string.split():

    x = re.match(r"bSw+", i)

    print(x.group())

Let’s run the code and see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
      1 for i in string.split():
      2     x = re.match(r"bSw+", i)
      3     print(x.group())
      4 

AttributeError: 'NoneType' object has no attribute 'group'

We raise the AttributeError because there is no match in the first iteration. Therefore x returns None. The attribute group() does not belong to NoneType objects.

Solution

To solve this error, we want to only call group() for the situation where there is a match to the regular expression. We can therefore use the try-except block to handle the AttributeError. We can use continue to skip when x returns None in the for loop. Let’s look at the revised code.

import re

# Search for an upper case "S" character in the beginning of a word then print the word

string = "Research Scientist"
for i in string.split():
    x = re.match(r"bSw+", i)
    try:
        print(x.group())
    except AttributeError:
        continue
Scientist

We can see that the code prints out Scientist, which is the word that has an upper case “S” character.

Example #4: Handling Modules

We can encounter an AttributeError while working with modules because we may call a function that does not exist for a module. Let’s look at an example of importing the math module and calling a function to perform a square root.

import math

number = 9

square_root_number = math.square_root(number)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
1 square_root_number = math.square_root(number)

AttributeError: module 'math' has no attribute 'square_root'

The module math does not contain the attribute square_root. Therefore we get an AttributeError.

Solution

To solve this error, you can use the help() function to get the module’s documentation, including the functions that belong to the module. We can use the help function on the math module to see which function corresponds to the square root.

import math

help(math)
  sqrt(x, /)

        Return the square root of x.

The function’s name to return the square root of a number is sqrt(). We can use this function in place of the incorrect function name.

square_root_number = math.sqrt(number)

print(square_root_number)
3.0

The code successfully returns the square root of 9. You can also use help() on classes defined in your program. Let’s look at the example of using help() on the Electron class.

help(Electron)

class Electron(builtins.object)
 |  Methods defined here:
 |  
 |  __init__(self)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  get_mass(self)
 |  
 |  positron(self)

The help() function returns the methods defined for the Electron class.

Summary

Congratulations on reading to the end of this tutorial. Attribute errors occur in Python when you try to reference an invalid attribute.

  • If the attribute you want for built-in data types does not exist, you should look for an attribute that does something similar. For example, there is no append() method for strings but you can use concatenation to combine strings.
  • For classes that are defined in your code, you can use help() to find out if an attribute exists before trying to reference it. If it does not exist you can add it to your class and then create a new instance of the class.
  • If you are not sure if a function or value does not exist or if a code block may return a NoneType object, you can wrap the code in a try-except statement. Using a try-except stops your program from crashing if you raise an AttributeError.

For further reading on AttributeError, you can go to the following article: How to Solve Python AttributeError: ‘list’ object has no attribute ‘split’

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

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

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

Добавить комментарий