简体   繁体   中英

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

As per Method resolution order, the members are searched in depth first search methodology ie 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 ie 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 ie class A

For eg:

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM