0

I've stumbled upon a somewhat confusing behaviour related to multiple inheritance. Consider the following setting:

class Parent1: def __init__(self): super().__init__() print(f"Hello from Parent1") class Parent2: def __init__(self): super().__init__() print(f"Hello from Parent2") class Child(Parent1, Parent2): def __init__(self): super().__init__() print(f"Hello from Child") c = Child() 

I saw it already in another question that for all parent classes to be initialised, each of them should call the object's __init__ method too. I tried to include or omit the super().__init__() calls in the parent classes in different configurations to see how it actually works. The result was a bit confusing: it seems that in particular, I need to call super in the first parent class to have the second one initialised too. In other words, if I omit the super() call in Parent1 (and keep it or omit it in Parent2, no difference), only Parent1 is initialised. I'm just trying to understand why it is like that - especially considering that the Method Resolution Order doesn't actually seem to be affected; the output of Child.mro() was completely independent of the super calls:

>>> Child.mro() [<class '__main__.Child'>, <class '__main__.Parent1'>, <class '__main__.Parent2'>, <class 'object'>] 

Even more surprisingly, even though Parent1 precedes Parent2 in MRO, it was always Parent2 that was getting initialised first (of course, in settings where both parent classes were initialised).

2
  • I don't really understand what you are asking. "I saw it already in another question that for all parent classes to be initialised, each of them should call the object's __init__ method too." The answer in that question doesn't state that each of them should call object.__init__... It doesn't say that anywhere. In any case, of course you require super() in Parent1, how else do you expect Parent2.__init__ to be called? "the output of Child.mro() was completely independent of the super calls:" Yes, of course. The .mro() isn't affected by that at all. Commented Dec 11, 2020 at 12:25
  • "Even more surprisingly, even though Parent1 precedes Parent2 in MRO, it was always Parent2 that was getting initialised first (of course, in settings where both parent classes were initialised)." Huh? In the code you've provided, the order of the calls is Child.__init__, Parent1.__init__, and finally Parent2.__init__... I think you are getting confused because you print after the call to super, put the print before. Commented Dec 11, 2020 at 12:26

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.