Nitin Kothari
Nitin Kothari

Reputation: 97

Multiple inheritance | Python

Why A is not called in this code: [is it because of mro : left to right then A class should be called?]

class A:
    
     def __init__(self,name):
        print('inside a',name)
        
class B:
    
     def __init__(self,name):
        print('inside b',name)
        
class C(B,A):
    
     def __init__(self,name):
        print('inside c',name)
        super().__init__(name)
        
c = C('hello')

Output :

inside c hello

inside b hello

But when I defined it like this basically a parent class then it is working properly as expected.[Why A class is called here ]Code:

class D:
    
    def __init__(self,name):
        print('inside d',name)
    
class A(D):
    
     def __init__(self,name):
        print('inside a',name)
        super().__init__(name)
        
class B(D):
    
     def __init__(self,name):
        print('inside b',name)
        super().__init__(name)
        
class C(B,A):
    
    def __init__(self,name):
        print('inside c',name)
        super().__init__(name)
        
c = C('hello')

output:

inside c hello

inside b hello

inside a hello

inside d hello

Upvotes: 0

Views: 195

Answers (1)

Tomato Master
Tomato Master

Reputation: 528

As per Method resolution order, the members are searched in depth first search methodology i.e in your first example :

class A:
    
     def __init__(self,name):
        print('inside a',name)
class B:
    
     def __init__(self,name):
        print('inside b',name)       


class C(B,A):
    
     def __init__(self,name):
        print('inside c',name)
        super().__init__(name)
        
c = C('hello')

First: constructor of C is called.

Second: Since you have super().init(name) in you class C , it will call its left parent i.e B.

Third: it will try to go to right(class C) but since you have not written super().init(name) inside class B ,the constructor of class A can't be called because from class B it can't move to Object class

                            Object
                             /\
                            /  \
                           B    A
                            \  /
                             \/
                             C 

If you will write super().init(name) in class B , it will iterate from Object class to right of object i.e class A

For e.g.:

class A:
    
     def __init__(self,name):
        print('inside a',name)
        
class B:

     def __init__(self,name):
        print('inside b',name)
        super().__init__(name)

        
class C(B,A):
    
     def __init__(self,name):
        print('inside c',name)
        super().__init__(name)

        
c = C('hello')

For more visit :https://www.geeksforgeeks.org/method-resolution-order-in-python-inheritance/

Upvotes: 2

Related Questions