Skip to content Skip to sidebar Skip to footer

Why Is My Superclass Calling My Subclass Method?

When I call a method that was overrided from my constructor, I am getting an error and it says that it is missing an argument (due to the subclass requiring a second argument). How

Solution 1:

The answer is that a base class that calls a method that is defined on itself, but also overridden by a subclass, calls the overridden method on the subclass not the method on the base class. For further information see calling an overridden method from base class?. See the below variant of your code and follow the logic as described above.

classA:def__init__(self):
        self.do()

    defdo(self):
        print("do A")


classB(A):def__init__(self):
        super().__init__()
        self.do()

    defdo(self):
        super().do()
        print("do B")


b = B()

Result: A B A B

Solution 2:

This is really curious. I don't have a solution but the below appears to work as intended. It is exactly the same except for super() is called explicitly with self.class as an argument, which I thought was implicit.

Maybe a more skilled Pythonista can build on this observation.

classA:def__init__(self):
        self.do()

    defdo(self):
        print("A")

classB(A):def__init__(self):
        super(self.__class__).__init__()
        self.do("B")

    defdo(self, arg2):
        super().do()
        print(arg2)

print('***init A***')
a = A()
print('***init B***')
b = B()
print('***A.do()***')
a.do()
print('***B.do()***')
b.do('test')

Post a Comment for "Why Is My Superclass Calling My Subclass Method?"