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

Asked

Viewed 249 times

0

Hello, I’m making inheritance in python and I’m 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 class builder A and add one more parameter in the class constructor B.

  • 2

    B(a,b,c), you’re calling the __init__ of B with three arguments when the function signature expects only one

  • As I would for instantiating class B and using the constructor parameters a,b of class A and also the new parameter c of class B?

  • Are you working on legacy code or are you just studying? If you are studying I advise you to study python3, otherwise good luck. : D

1 answer

6


One of the precepts of language is:

Explicit is better than implicit.

So don’t expect anything magical python. You have defined the method B.__init__ two-parameter, self and c, then when to instantiate B you must inform only the value of c - since self will be defined by the language.

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

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

But as the class A is who works with the values of a and b, you will need to explicitly pass these values to the A:

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

See working on Repl.it

Thus, all classes will be initialized with their proper values. Remember that when you define the method __init__ in the child class you will override the mother class method, so you need the explicit call of the mother class. Read on Order of Method Resolution to understand how the call sequence is defined.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.