2017-09-21 73 views
0

这是一个采访示例问题我复制并从问题10改性: https://www.codementor.io/sheena/essential-python-interview-questions-du107ozr6蟒多重继承qustion

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()示出了“停一停!”因为b不会覆盖stop(),所以会从A继承stop()。

但是我不明白为什么调用d.stop()只显示A,C,D, :D-> B-> C-> A?

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

我一定有误解......。关于超我猜。

回答

2

我知道调用b.stop()会显示“stop A stop!”因为B不 载停机(),因此将从A.

继承停止(),但我不明白为什么叫d.stop()只显示A,C,d的停止, 不ACBD,ISN” MRO:D-> B-> C-> A?

B,从A继承stop,但是这是什么意思是,当您尝试访问B.stopsome_B_instance.stop,属性搜索将寻找在B.__dict__后发现,通过A.__dict__的方法。它不直接将该方法放在B类中。

super遵循D实例的MRO时,B类在D之后,但super只关心在这一点上B本身,而不是B的祖先。它在B.__dict__中查找stop条目,而不考虑继承的方法;继承的方法将在稍后的搜索中处理,当super达到这些方法从中继承的类。

由于继承方法实际上并未将它们置于B.__dict__,super中,因此在B中找不到stop

+0

好吧,所以“超级只关心看B本身不是祖先”,。得到它了。谢谢。 – user389955

1

B没有自己的stop(你会注意到字符串"stop B stop"从未出现在代码中),所以它永远不会被执行。在其他情况下,由于没有可能打印“停止B停止”的代码行,所以它不会被打印。

+0

但调用b.stop()显示“停止停止!”,这意味着b.stop()可用? – user389955

+0

是的,但它显示为“停止停止!”,即使它是b.stop –

+0

B没有*自己的停止。它从'A'继承'stop'。 –