看板 Python 關於我們 聯絡資訊
Os環境:Win7 Py版本: 3.8.10 請看一下以下的程式碼: #-------------------------------- class a: def __init__(self): print("init of a!!") class b: def __init__(self): print("init of b!!") class c: def __init__(self): print("init of c!!") class d(a,b,c): def __init__(self): print("enter d!!") super().__init__() super(a, self).__init__() super(b, self).__init__() super(c, self).__init__() print("d end!!") d_o = d() #------------------------------- 輸出: enter d!! init of a!! <-- super().__init__() 的結果 init of b!! <-- super(a, self).__init__() 的結果 init of c!! <-- super(b, self).__init__() 的結果 d end!! 這結果想不通,經過交叉確認後, 發現是 super(c, self).__init__() 這行沒輸出。 請問不能指定執行哪個父類別的建構式(__init__)嗎? 而且指定父類別後,還會往繼承順序後方後跳一個? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.243.134.206 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1648020979.A.221.html
lycantrope: Method Resolution Order 可以看一下 03/23 16:04
lycantrope: super() 與super(d,self)等價 就是呼叫d類別下一個mro 03/23 16:12
lycantrope: d.__mro__有順序,同理super(c,self)會呼叫object 03/23 16:13
lycantrope: __init__會看不到任何輸出(c的super是object) 03/23 16:14
pshuang: 原來如此 感謝 03/23 16:32