TypeError: Child2.__init__() missing 1 required positional argument: 'c'

34 views Asked by At
class Parent:
    def __init__(self, a):
        self.a = a


class Child1(Parent):
    def __init__(self, a, b):
        super().__init__(a)
        self.b = b


class Child2(Parent):
    def __init__(self, a, c):
        super().__init__(a)
        self.c = c


class GrandChild(Child1, Child2):
    def __init__(self, a, b, c):
        Child1.__init__(self, a, b)
        Child2.__init__(self, a, c)

    def addition(self):
        return self.a + self.b + self.c


res = GrandChild(1, 2, 3)
res.addition()

I am trying to add 3 number using hybrid inheritance and complier showing

TypeError:Child2.init() missing 1 required positional argument: 'c'

Any help would be appreciable

1

There are 1 answers

0
chepner On

The correct way to use super with __init__ is to

  1. Use keyword arguments when instantiating the class.
  2. Define __init__ with only those parameters you need to use directly, and to accept arbitrary keyword arguments.
  3. Always call super().__init__ once, passing any keyword arguments you don't know what to do with.
class Parent:
    def __init__(self, *, a, **kwargs):
        super().__init__(**kwargs)
        self.a = a


class Child1(Parent):
    def __init__(self, *, b, **kwargs):
        super().__init__(**kwargs)
        self.b = b


class Child2(Parent):
    def __init__(self, *, c, **kwargs):
        super().__init__(**kwargs)
        self.c = c


class GrandChild(Child1, Child2):
    # __init__ doesn't even need to be overriden here.

    def addition(self):
        return self.a + self.b + self.c

res = GrandChild(a=1, b=2, c=3)

See https://rhettinger.wordpress.com/2011/05/26/super-considered-super/ for an explanation of the 3 rules listed above.