python多继承初始化对象中的属性


主要是开发过程中遇见了新坑

在访问多继承中次类对象属性的时候,发现无法访问

解决参考 stackoverflow 的 回答

 

补充:

python mro的算法主要 DFS --> BFS --> C3算法  参考 http://python.jobbole.com/85685/

 

代码如下: 

class A(object):
    def __init__(self):
        print('Running A.__init__')
        super(A,self).__init__()
        
class B(A):
    def __init__(self):
        print('Running B.__init__')
        # super(B,self).__init__()
        A.__init__(self) class C(A):
    def __init__(self):
        print('Running C.__init__')
        super(C,self).__init__()
        
class D(B,C):
    def __init__(self):
        print('Running D.__init__')
        super(D,self).__init__()

foo=D()

结果

Running D.__init__
Running B.__init__
Running A.__init__

如果把 A.__init__ (self) 替换成 super(B, self).__init__(), 就可以看到我们想看到的结果

Running D.__init__
Running B.__init__
Running C.__init__
Running A.__init__

原因如下:

Holy smokes, B knows nothing about C, and yet super(B,self) knows to call C's __init__? The reason is because self.__class__.mro() contains C. In other words, self (or in the above, foo) knows about C. ---unutbu

也就是说,若果在 B 中没有调用 super 方法, B 不知道 C 也在 mro 中,所以不会 __init__ C。

over。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM