Search code examples
pythonmethodsoverridingsuperattributeerror

How to solve AttributeError caused by overriden method


I try to find the reason I get an Attribute error when I override a method in a subclass that access a attribute introduced in that subclass.

In the code below you can see that B works fine, but the error only occurs when I reference the new attribute in the overridden method in C.

I thought that I maybe had to call the populate method again, but that seems not to be the case.

# some class that uses a method to populate one of it's attributes
class A:
    def __init__(self):
        self.populate()

    # The original populating method
    def populate(self):
        self.x = 5

my_obj = A()
print(my_obj.x)

# I can make a subclass that works fine AND has a new attribute
class B(A):
    def __init__(self):
        super().__init__()
        self.y = 9

    def populate(self):
        self.x = 5

my_obj = B()
print(my_obj.x)
print(my_obj.y)


class C(A):
    def __init__(self):
        super().__init__()
        self.z = 7
        self.populate()

    # This method overides the original one and causes an attribute error
    # because self.z is unknown
    def populate(self):
        self.x = self.z

my_obj = C()
print(my_obj.x)

Solution

  • The problem is that you need the attribute x when initializing your object C. In A.__init__ the call to self.populate() is already the overriding method, i.e. C.populate and it requires self.x.

    You can set self.z before calling the parent's __init__ method:

    class C(A):
        def __init__(self):
            self.z = 7
            super().__init__()
    
        def populate(self):
            self.x = self.z