1

I have some class structure like this:

class A:
    def __init__(self):
        print("A")
class B:
    def __init__(self, x):
        print("B")

class C(A,B):
    def __init__(self):
        super(C, self).__init__() # ???

c=C()

As you can see, A and B both are parent class of C. I want to call both classes __init__ in C's __init__. I want to pass some parameter to B's __init__. Is there any way I can do this with super keyword? I think that this will work:

class C(A,B):
    def __init__(self):
        A.__init__()
        B.__init__(5)

Should we call __init__ directly in such a way, or is there any better solution for this?

Pratik
  • 1,351
  • 1
  • 20
  • 37
  • The prerequisite for cooperative super calls is that all the inherited methods have compatible signature throughout the whole hierarchy. If you're interested only in implementation reuse, composition/delegation may be a better design choice than multiple inheritance (depending on the context etc). – bruno desthuilliers Jan 07 '20 at 08:12

1 Answers1

1

You have to provide self as parameter to parent classes' __init__().

class C(A,B):
def __init__(self):
    A.__init__(self)
    B.__init__(self, 5)
Valentin M.
  • 520
  • 5
  • 19