在 Python returns 奇数结果中使用 super() 的多级和多重继承
Multilevel and Multiple inheritance using super() in Python returns odd result
如果我输入这段代码,
class A:
pass
class B(A):
def show_letter(self):
print("This is B")
class C(B):
def show_letter(self):
super().show_letter()
print("This is C")
class E(B):
def show_letter(self):
super().show_letter()
print("This is E")
class D(C, E):
division = "North"
def show_letter(self):
super().show_letter()
print("This is D")
div1 = D()
div1.show_letter()
它returns:
This is B
This is E
This is C
This is D
为什么印有“E”?
如果我在 C class 中删除 super(),则不会打印“E”。
谢谢。
这是因为the method resolution order。第一次调用在 D
中,然后由于参数顺序调用 C
:D(C, E)
。它可以调用 B
作为父对象,但后者也是 E
的父对象,因此它被称为第一个。只有在那之后才会有一个 B
电话。因此,您的调用顺序是 D -> C -> E -> B 并且 print
顺序受到尊重。
如果我输入这段代码,
class A:
pass
class B(A):
def show_letter(self):
print("This is B")
class C(B):
def show_letter(self):
super().show_letter()
print("This is C")
class E(B):
def show_letter(self):
super().show_letter()
print("This is E")
class D(C, E):
division = "North"
def show_letter(self):
super().show_letter()
print("This is D")
div1 = D()
div1.show_letter()
它returns:
This is B
This is E
This is C
This is D
为什么印有“E”? 如果我在 C class 中删除 super(),则不会打印“E”。 谢谢。
这是因为the method resolution order。第一次调用在 D
中,然后由于参数顺序调用 C
:D(C, E)
。它可以调用 B
作为父对象,但后者也是 E
的父对象,因此它被称为第一个。只有在那之后才会有一个 B
电话。因此,您的调用顺序是 D -> C -> E -> B 并且 print
顺序受到尊重。