Skip to content

How to Resolve "AttributeError: 'ClassName' object has no attribute 'attribute_name'" in Python

Fix Python's AttributeError when accessing undefined attributes or methods in classes, covering typos, indentation, and inheritance issues with step-by-step solutions.

When working with classes in Python, the AttributeError: 'X' object has no attribute 'Y' is one of the most common exceptions you will encounter. It is raised when you try to access an attribute or call a method on an object, but the name you've referenced doesn't exist for that specific instance. This can happen for several reasons, including simple typos, incorrect indentation, or issues with class inheritance.

This guide will walk you through the primary causes of this error and provide clear, step-by-step solutions to fix them, ensuring your object-oriented code works as expected.

Understanding the AttributeError

Every object in Python has a "namespace", which is a collection of names (attributes and methods) that are valid for it. The AttributeError simply means that the name you are trying to access (e.g., .eat(), .age) is not found in that object's namespace at that moment.

Cause 1: Typo or Non-Existent Attribute/Method

The most straightforward cause is a simple spelling mistake or trying to access an attribute or method that you haven't defined in the class yet.

Example of code causing the error:

class Human:
    def __init__(self, name):
        self.name = name
    
    def walk(self):
        print(f"{self.name} is walking.")

person = Human("John")

try:
    print(person.age)
except AttributeError as e:
    print(f"Error accessing attribute: {e}")

try:
    person.eat()
except AttributeError as e:
    print(f"Error calling method: {e}")

Output:

Error accessing attribute: 'Human' object has no attribute 'age'
Error calling method: 'Human' object has no attribute 'eat'

Solution: the fix is to define the missing attribute and method in the class definition. Attributes are typically defined within the __init__ method.

class Human:
    def __init__(self, name, age):
        self.name = name
        self.age = age  # ✅ Define the 'age' attribute
    
    def walk(self):
        print(f"{self.name} is walking.")

    def eat(self):      # ✅ Define the 'eat' method
        print(f"{self.name} is eating.")

person = Human("John", 30)

print(person.age)
person.eat()

Output:

30
John is eating.

Cause 2: Incorrect Indentation

Python uses indentation to define code blocks and scope. If a method is not indented correctly, it will not be considered part of the class, even if it is physically located right after it.

Example of code causing the error:

class Human:
    def __init__(self, name):
        self.name = name

def walk(self):
    print("Walking")

person = Human("John")

try:
    person.walk()
except AttributeError as e:
    print(f"Error: {e}")

Output:

Error: 'Human' object has no attribute 'walk'

Solution: ensure all methods and class-level attributes are indented correctly (usually by 4 spaces) so they are properly scoped within the class block.

class Human:
    def __init__(self, name):
        self.name = name

    def walk(self):
        print(f"{self.name} is walking.")

person = Human("John")
person.walk()

Output:

John is walking.

Cause 3: Attribute Defined in an __init__ Method That Was Not Called

This is a common issue in class inheritance. If a child class defines its own __init__ method but fails to call the parent's __init__ method using super(), any attributes defined in the parent's __init__ will not be created for the child instance.

Example of code causing the error:

class Animal:
    def __init__(self, name):
        print("Animal __init__ called.")
        self.name = name # This attribute is created here

class Dog(Animal):
    def __init__(self, breed):
        print("Dog __init__ called.")
        self.breed = breed

my_dog = Dog("Beagle")

try:
    print(my_dog.name) 
except AttributeError as e:
    print(f"Error: {e}")

Output:

Dog __init__ called.
Error: 'Dog' object has no attribute 'name'

Solution: always call super().__init__() within the child class's __init__ method to ensure the parent class is properly initialized.

class Animal:
    def __init__(self, name):
        print("Animal __init__ called.")
        self.name = name

class Dog(Animal):
    def __init__(self, name, breed):
        print("Dog __init__ called.")
        super().__init__(name)
        self.breed = breed

my_dog = Dog("Fido", "Beagle")
print(my_dog.name)
print(my_dog.breed)

Output:

Dog __init__ called.
Animal __init__ called.
Fido
Beagle

Debugging Tips to Find the Problem

If you are unsure what attributes an object has, you can use these built-in functions to inspect it:

  • dir(object): Returns a list of all valid attributes and methods for that object.
  • object.__dict__: Returns a dictionary of the instance's attributes.
class Car:
    def __init__(self, brand):
        self.brand = brand

my_car = Car("Ford")

print(f"dir(my_car): {dir(my_car)}")

print(f"my_car.__dict__: {my_car.__dict__}")

Output:

dir(my_car): ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'brand']
my_car.__dict__: {'brand': 'Ford'}

Conclusion

The AttributeError: 'object' has no attribute is a fundamental error in object-oriented Python that is almost always caused by one of three issues:

  1. A typo or missing definition: Double-check the spelling and ensure the attribute or method is actually defined in your class.
  2. Incorrect indentation: Verify that your methods are properly indented to be part of the class.
  3. An uncalled parent __init__: If you are using inheritance, ensure you call super().__init__(...) in your child class's constructor.

By systematically checking these three points, you can quickly diagnose and resolve this common error.

Navigation