[問題] 關於多重繼承與super的呼叫問題

看板Python作者 (中山先生忠實信徒-我愛蘿)時間2年前 (2022/03/23 15:36), 編輯推噓2(203)
留言5則, 2人參與, 2年前最新討論串1/1
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

03/23 16:04, 2年前 , 1F
Method Resolution Order 可以看一下
03/23 16:04, 1F

03/23 16:12, 2年前 , 2F
super() 與super(d,self)等價 就是呼叫d類別下一個mro
03/23 16:12, 2F

03/23 16:13, 2年前 , 3F
d.__mro__有順序,同理super(c,self)會呼叫object
03/23 16:13, 3F

03/23 16:14, 2年前 , 4F
__init__會看不到任何輸出(c的super是object)
03/23 16:14, 4F

03/23 16:32, 2年前 , 5F
原來如此 感謝
03/23 16:32, 5F
文章代碼(AID): #1YEitp8X (Python)