How to inform parameters to the initializer of the parent class with Python?

0

Hello, I'm doing inheritance in python and am encountering the following error:

  

TypeError: __init__() takes exactly 2 positional arguments (4 given)

class A():
    def __init__(self,a,b):
        self.a = a
        self.b = b

class B(A):
    def __init__(self,c):
        self.c = c
        super().__init__(self)


if __name__ == '__main__':
    a =10
    b = 5
    c = 8
    teste = B(a,b,c)

In class B I would like to use the constructor of class A and add another parameter in the constructor of class B .

    
asked by anonymous 18.09.2018 / 12:44

1 answer

6

One of the language precepts is:

  

Explicit is better than implicit.

So do not expect anything magic from Python. You have defined the B.__init__ method with two parameters, self and c , so when instantiating B you should only enter the value of c - since self will be defined by the language.

If you need the class B to have all three parameters, a , b and c you will need to define them explicitly.

class B(A):
    def __init__(self, a, b, c):
        ...

But since the A class works with the values of a and b , you need to explicitly pass those values to the A instance:

class B(A):
    def __init__(self, a, b, c):
        self.c = c
        super().__init__(a, b)
        #                ^--- Não precisa de self aqui

See working at Repl.it

Thus, all classes will be initialized with their proper values. Remember that when you set the __init__ method in the child class you will overwrite the method of the parent class, so you need to explicitly call it. Read about Method Resolution Order to understand how the call string is defined.

    
18.09.2018 / 13:27