python 多重继承问题

python multiple inheritance qustion

这是我从问题 10 复制和修改的面试示例问题: https://www.codementor.io/sheena/essential-python-interview-questions-du107ozr6

class A(object):
    def go(self):
        print("go A go!")
    def stop(self):
        print("stop A stop!")

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!")
    def stop(self):
        super(C, self).stop()
        print("stop C stop!")

class D(B,C):
    def go(self):
        super(D, self).go()
        print("go D go!")
    def stop(self):
        super(D, self).stop()
        print("stop D stop!")

class E(B,C): pass
a = A()
b = B()
c = C()
d = D()
e = E()
print "call b.stop()......."
b.stop()
print "call d.stop()......."
d.stop()
print "call e.stop()......."
e.stop()

答案是:

call b.stop().......
stop A stop!
call d.stop().......
stop A stop!
stop C stop!    
stop D stop!  #?why not having b.stop() which leads to "stop A stop!"
call e.stop().......
stop A stop!
stop C stop!

我知道调用 b.stop() 显示 "stop A stop!" 因为 b 没有覆盖 stop() 所以将从 A 继承 stop()。

但是我不明白为什么调用d.stop()只显示A,C,D的停止,没有显示ACBD,不是MRO: D->B->C->A吗?

我不明白为什么调用 e.stop() 只显示 A 和 C 的停止,基于 MRO:E->B->C->A,我认为 e.stop( )应该继承自B的stop(),所以应该是stop A stop,stop C stop,然后stop B stop?

我一定是误会了某事。关于超级我猜。

B 没有自己的 stop(您会注意到字符串 "stop B stop" 从未出现在代码中),因此它永远不会被执行。更糟糕的是,由于没有一行代码可以打印 "stop B stop",因此不会打印。

I understand calling b.stop() shows "stop A stop!" because b does not override stop() so will inherit stop() from A.

But I do not understand why calling d.stop() only show stop of A,C,D, not ACBD, isn't MRO: D->B->C->A?

B继承了A的stop,但是这意味着当你尝试访问B.stopsome_B_instance.stop时,属性搜索将通过[=13=找到方法] 在 B.__dict__ 中查看后。它没有直接将方法放在 B class 中。

super在D实例的MRO之后,classB在D之后,但是super此时只对B本身感兴趣,而不是B的祖先.它在 B.__dict__ 中查找 stop 条目,而不考虑继承的方法;继承的方法将在稍后的搜索中处理,当 super 到达 classes 时,这些方法是从中继承的。

由于继承方法实际上并没有将它们放在 B.__dict__ 中,superB 中找不到 stop