2

I know how super works, it finds method from the previous base class by MRO.
So if I have two base classes A and B, and let class C inherit them, how should I use super to initialize A and B if they need parameters? Like this:

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

class B:
    def __init__(self, b):
        self.b = b

class C(A, B): # inherit from A and B
    def __init__(self, c):
        A.__init__(self, a=1)
        B.__init__(self, b=2) # How to use super here?
        self.c = c 

If I use super in each class, I need to ensure the correct inheritance order:

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

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

class C(A, B): # Here must be (A, B)
    def __init__(self, c, a):
        super().__init__(a=a)
        self.c = c

But this makes A and B coupled, which is really bad. How should I deal with such situation, i.e., initialize B by C? Don't use super? What is the most Pythonic way?

Hou Lu
  • 3,012
  • 2
  • 16
  • 23
  • 1
    Short answer: Don't use `super`. `super` only works with multiple inheritance if the base classes are designed for multiple inheritance. When you inherit from two unrelated classes, it's best to call their constructors explicitly. – Aran-Fey May 22 '18 at 09:07
  • Got it! Is this a bad design to inherit from two independent classes? – Hou Lu May 22 '18 at 09:26
  • That's debatable. Some say yes, others say no. Personally, I don't have a strong opinion on the topic. – Aran-Fey May 22 '18 at 09:29

0 Answers0