多重继承|蟒蛇

时间:2020-08-30 13:43:55

标签: python python-3.x inheritance multiple-inheritance

为什么在此代码中未调用A:[是因为mro:从左到右然后应调用A类?]

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')

输出:

inside c hello

inside b hello

但是当我这样定义它基本上是一个父类时,它就可以按预期正常工作。[为什么在这里调用一个类]代码:

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')

输出:

inside c hello

inside b hello

inside a hello

inside d hello

1 个答案:

答案 0 :(得分:2)

根据方法解析顺序,将对成员进行深度优先搜索,即在您的第一个示例中:

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')

首先:是C的构造函数。

第二个:由于您在C类中具有super()。 init (name),它将调用其左父对象,即B。

第三步:,它将尝试向右(C类)进行操作,但是由于您尚未编写super()。 init (名称)位于B类内部,因此构造函数不能调用A类的对象,因为它不能从B类移到Object类

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

如果要在类B中编写super()。 init (name),它将从Object类迭代到对象的右侧,即类A

例如:

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')

更多信息,请访问:https://www.geeksforgeeks.org/method-resolution-order-in-python-inheritance/