作者pshuang (中山先生忠实信徒-我爱萝)
看板Python
标题[问题] 关於多重继承与super的呼叫问题
时间Wed Mar 23 15:36:14 2022
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://webptt.com/cn.aspx?n=bbs/Python/M.1648020979.A.221.html
1F:推 lycantrope: Method Resolution Order 可以看一下 03/23 16:04
2F:推 lycantrope: super() 与super(d,self)等价 就是呼叫d类别下一个mro 03/23 16:12
3F:→ lycantrope: d.__mro__有顺序,同理super(c,self)会呼叫object 03/23 16:13
4F:→ lycantrope: __init__会看不到任何输出(c的super是object) 03/23 16:14
5F:→ pshuang: 原来如此 感谢 03/23 16:32