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?

3
  • 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. Commented May 22, 2018 at 9:07
  • Got it! Is this a bad design to inherit from two independent classes? Commented May 22, 2018 at 9:26
  • That's debatable. Some say yes, others say no. Personally, I don't have a strong opinion on the topic. Commented May 22, 2018 at 9:29

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.