2016-03-05 47 views
0

這是我的情況,我應該寫什麼來代替評論?Python3.4多繼承調用特定構造函數

非常感謝您,如果我問了一些問題,我很抱歉。

我已經找到了一個答案,但沒有成功。

#!/usr/bin/python3.4 
class A(object): 
    def __init__(self): 
     print("A constructor") 

class B(A): 
    def __init__(self): 
     super(B, self).__init__() 
     print("B constructor") 

class C(A): 
    def __init__(self): 
     super(C, self).__init__() 
     print("C constructor") 

class D(B,C): 
    def __init__(self): 
     """ what to put here in order to get printed: 
      B constructor 
      C constructor 
      A constructor 
      D constructor 
        or     
      C constructor 
      B constructor 
      A constructor 
      D constructor 
        ? 
      (notice I would like to print once 'A constructor') 
     """ 
     print("D constructor") 

if __name__ == "__main__": 
    d = D() 

回答

1

我發現改變了一點類的構造函數代碼做什麼,我需要:

#!/usr/bin/python3.4 
class A(object): 
    def __init__(self): 
     print("A constructor") 

class B(A): 
    def __init__(self): 
     if self.__class__ == B: 
      A.__init__(self) 
     print("B constructor") 

class C(A): 
    def __init__(self): 
     if self.__class__ == C: 
      A.__init__(self) 
     print("C constructor") 

class D(B,C): 
    def __init__(self): 
     B.__init__(self)  # 
     C.__init__(self)  # if B constructor should be 
     A.__init__(self)  # called before of C constructor 
     print("D constructor") # 

#  C.__init__(self)  # 
#  B.__init__(self)  # if C constructor should be 
#  A.__init__(self)  # called before of B constructor 
#  print("D constructor") # 

if __name__ == "__main__": 
    d = D()