How does Python's super() work with multiple inheritance?
我在看上面的问题/答案,把自己弄糊涂了
53 class First(object):
54 def __init__(self):
55 print "first"
56
57 class Second(First):
58 def __init__(self):
59 super(Second, self).__init__()
60 print "second"
61
62 class Third(First):
63 def __init__(self):
64 print "third"
65
66 class Fourth(Second, Third):
67 def __init__(self):
68 super(Fourth, self).__init__()
69 print "thats it"
Fourth()
third
second
thats it
53 class First(object):
54 def __init__(self):
55 print "first"
56
57 class Second(First):
58 def __init__(self):
59 #super(Second, self).__init__() <---- commented out
60 print "second"
61
62 class Third(First):
63 def __init__(self):
64 print "third"
65
66 class Fourth(Second, Third):
67 def __init__(self):
68 super(Fourth, self).__init__()
69 print "thats it"
Fourth()
second
thats it
有人可以向我解释一下为什么顶部打印 "third"
而底部不打印的原因吗?
我觉得在幕后发生了某种我没有看到的秩序/顺序。
-- 四.mro
在Second中注释掉super
(, , , , )
super 第二
(, , , , )
最佳答案
super
实际上并不调用父类(super class)。它根据方法解析顺序 (MRO) 调用下一个方法。您的示例类的 MRO 看起来如下所示:
Fourth
Second
Third
First
也就是说,使用 Fourth
中的 super
可以得到 Second
上的方法。使用 Second
中的 super
可以获得 Third
上的方法。等
在第一个例子中:
Fourth.__init__
被调用。Fourth.__init__
通过super
调用Second.__init__
。Second.__init__
通过super
调用Third.__init__
。Third.__init__
打印“third”Second.__init__
打印“second”Fourth.__init__
打印“就是这样”。
在第二个例子中:
Fourth.__init__
被调用。Fourth.__init__
通过super
调用Second.__init__
。Second.__init__
打印“second”Fourth.__init__
打印“就是这样”。
所以,是的,更改 Second
中的 super
调用会改变是否调用 Third
上的某些内容,即使 Third
不是 Second
的父类(super class)。这确实令人费解。我推荐阅读 "Python's Super is nifty, but you can't use it" .这就是我读到的解释,上面的内容对我来说是有意义的。
关于python - 使用多重继承时如何使用super来初始化所有父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19365574/