[英]In python why does super behave this way with multiple inheritance?
So we have a code snippet below. 因此,我们在下面有一个代码段。 I don't understand why it behave this way. 我不明白为什么会这样。 Why does super(B, self).go()
resolves to the go
method of the C
class? 为什么super(B, self).go()
解析为C
类的go
方法?
class A(object):
def go(self):
print("go A go!")
class B(A):
def go(self):
super(B, self).go()
print("go B go!")
class C(A):
def go(self):
super(C, self).go()
print("go C go!")
class D(B, C):
def go(self):
super(D, self).go()
print("go D go!")
d = D()
d.go()
# go A go!
# go C go!
# go B go!
# go D go!
Despite its name, super
does not necessarily refer to a superclass. 尽管其名称很高,但super
不一定是指超类。 super(B, self)
refers to the class in self
's MRO that follows B
. super(B, self)
指self
的MRO中紧随B
。
You can see the MRO for D with 您可以看到D的MRO
>>> D.__mro__
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)
This means that from d.go
, super(D, self)
refers to B
. 这意味着从d.go
, super(D, self)
指向B
When B.go
is called as a result, super(B, self)
refers to C
, not A
. 结果调用B.go
, super(B, self)
引用C
, 而不是 A
This is because self
is still an instance of D
, so it is D.__mro__
that dictates what gets called next, not the static superclass of B
. 这是因为self
仍然是D
的实例,因此是D.__mro__
决定接下来要调用的内容,而不是B
的静态超类。
The most important thing to remember about super
is that inside Foo.go
, you do not know what class super(Foo, self)
will refer to, because you do not know if self
is an instance of Foo
or a descendent of Foo
. 要记住,最重要的super
是里面Foo.go
,你不知道什么类super(Foo, self)
将会参考,因为你不知道self
是一个实例Foo
或后代Foo
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.