1

I have the following piece of code implementing multiple inheritance. I expect the call super(base2,self).__init__() to print --> "Printing from base2". But the program prints nothing; neither it throws error.

class base1:
    def __init__(self):
        print("printing from base1")
    
    def method(self,val):
        print("From method of base1", val)

class base2:
    def __init__(self):
        print("printing from base2")
    
    def method(self,val):
        print("From method of base2", val)
        
class child(base1, base2):
    def __init__(self):
        super(base2,self).__init__()  #is not working as expected
        
        
x = child() 
Pavan kumar
  • 478
  • 3
  • 16
user3103957
  • 636
  • 4
  • 16
  • Does this answer your question? [How does Python's super() work with multiple inheritance?](https://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with-multiple-inheritance) – David Jun 27 '20 at 08:03
  • Thanks for looking into this. I actually get the concept of MRO. In my case, I am not quite understanding why it is not printing. At least it should throw error. But it is not. – user3103957 Jun 27 '20 at 08:15

1 Answers1

2

The call to super expects the child class as its first param, not the base class. You should be doing

super(child, self).__init__()

However, since python 3.0, you can simply do

super().__init__()

But how does this play into multiple inheritence? Well that's extremely well explained in this answer

Basically, in your case, changing super to the appropriate call will yield the base1 class' __init__ call. According to the MRO (method resolution order).

What if you wanted to invoke the __init__ of base2? Well you're looking into directly calling base2.__init__() in that case, or simply changing the order of inheritance.

class child(base2, base1):
    def __init__(self):
        super().__init__()

Now this will print the base2 class' __init__ method

Chase
  • 5,315
  • 2
  • 15
  • 41
  • Thanks for your reply. If I understand correctly, in super(classname,arg1, arg2..), always the class name needs to be a child class in the inheritance hierarchy. Else it wont work as expected. Am I understanding correct ? – user3103957 Jun 27 '20 at 08:17
  • 1
    @user3103957 the `classname` in `super`'s first argument should be the *class who's super will be called*, so `super(foo, self)` will call the superclass of `foo`. – Chase Jun 27 '20 at 08:18