Search code examples
pythoninheritancesuper

The __init__() method gets overridden even though I used super(). Why?


As in the title I initiated the super class __init__ method in the inheriting class __init__ method but it still gets overriden, or at least I think it does. I want the self.x = x to work in the inheriting class too.

class Abs(ABC):
    def __init__(self, x: int = 1, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.x = x

    @abstractmethod
    def foo(self):
        pass

class Con(Abs):
    def __init__(self, x: int = 1, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

    def foo(self):
        print(self.x)

obj = Con(x=4)
obj.foo() # <---- this here returns 1 instead of 4

Solution

  • This is because you're not passing x on in your super call. It should be:

    def __init__(self, x: int = 1, *args, **kwargs) -> None:
        super().__init__(x, *args, **kwargs)
    

    However, note that this method is completely pointless. You should only override a method if you want to do something different from the superclass version. In this case you don't; you should remove the method completely from Con.