我正在学习继承,遇到了这个问题
class A:
def test(self):
print("test of A called")
class B(A):
def test(self):
print("test of B called")
super().test()
class C(A):
def test(self):
print("test of C called")
super().test()
class D(B,C):
def test2(self):
print("test of D called")
obj=D()
obj.test()
输出如下所示,根据张贴该ques的网站
test of B called
test of C called
test of A called
但在我看来,输出应该是
test of B called
test of A called
因为,类B将首先被调用(Acc到MRO(,然后从类B调用super().test()
,它将打印CCD_ 2。
我哪里错了?
简短回答:当B.test
调用super().test()
时,它使用原始对象的MRO。它不仅仅着眼于B
的层次结构。
粘贴您的代码[http://pythontutor.com/visualize.html][1] 和Visulize一行一行。我希望它能有所帮助。