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