0
class father:
    def __init__(self):
        print("Dad")

class mother:
    def __init__(self):
        print("Mom")
        
class child(father,mother):
    def __init__(self):
        super().__init__()
        print("Child")
        
child()

Output:

Dad
Child

How to do it correctly such that the mother is initialized as well?

I understand this problem has been addressed previously, but I can only find either long explanations about MRO or modifications to the father and mother class, which is in my case not allowed. I'm sure this problem is more trivial than that...

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    Add `super().__init__` calls to all `__init__`s? – Tomerikoo Dec 08 '20 at 10:47
  • It's there in the child class – Django the Giant Dec 08 '20 at 10:48
  • 1
    ***All `__init__`s***. That means in `father` and `mother` as well. Right now your `super` call goes to the `father`'s `__init__`, prints `Dad` and goes back to `child`. You need to add another `super` call there as well in order for it to go to the `mother`'s `__init__` as well – Tomerikoo Dec 08 '20 at 10:49
  • As mentioned above and to see how ```super``` go through your code, you can simple print out ```child.mro()```. Despite that, unless you are really well prepared, I don't recommend to use ```super()``` at all. – Henry Tjhia Dec 08 '20 at 10:51
  • @Tomerikoo is this possible without changing the mother and father constructors? – Django the Giant Dec 08 '20 at 10:56
  • I guess you can do something like `for cls in child.mro()[1:]: cls.__init__(self)` but I doubt that's considered good design... – Tomerikoo Dec 08 '20 at 10:58
  • 1
    @HenryTjhia Why you don't recommend to use `super()`? That's the idiomatic way of calling the parent... – Tomerikoo Dec 08 '20 at 11:01
  • @Tomerikoo Well, because explicitly calling a parent of a subclass is better. I agree that ```super``` has it place, but it will make your code more complex when it come to multiple inheritance. – Henry Tjhia Dec 08 '20 at 11:10
  • 1
    Calling `super()` isn't simply idiomatic, it the right way to do it, especially if multiple inheritance is involved. – martineau Dec 08 '20 at 11:10
  • @HenryTjhia that is completely not true. Using hard-coded parent class is the wrong way of doing inheritance. `super` ***does not*** make the code more complex, it rather simplifies it and makes it moer generic (what if you decide to change the inheritance list of a class? Even just its order?) – Tomerikoo Dec 08 '20 at 11:12

0 Answers0