[Python] Why does __init__ requires an explicit self as an argument when calling it as...

Discussão em 'Python' iniciado por Stack, Abril 28, 2025.

  1. Stack

    Stack Membro Participativo

    I know of two ways to call a superclass's constructor from a derived class: super().__init__() and base.__init__(self). Why does the second require me to explicitly supply self as an argument?

    Here's a snippet that demonstrates the difference:

    class base:
    def __init__(self,/):
    print("initializing")

    class der(base):
    def __init__(self):
    super().__init__() #no error
    base.__init__(self) #no error
    base.__init__() #error, self required

    obj = der()


    The third constructor call throws this error:

    File "demo.py", line 11, in <module>
    obj = der()
    ^^^^^
    File "demo.py", line 9, in __init__
    base.__init__() #error, should be: base.__init__(self)
    ^^^^^^^^^^^^^^^
    TypeError: base.__init__() missing 1 required positional argument: 'self'


    I expect base.__init__() to work since super().__init__() doesn't require an explicit self.

    Continue reading...

Compartilhe esta Página