了解继承的意外结果

阿曼(Aman raheja)

我正在学习继承并且遇到了这个问题

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()

根据此问题发布的网站,输出如下

test of B called
test of C called
test of A called

但我认为输出应为

test of B called
test of A called

因为,将首先调用类B(从Acc到MRO),然后super().test()从将打印的类B进行调用test of A called

我在哪里错了?

路德

简短的答案:B.test调用时super().test(),它将使用原始对象的MRO。它不只是查看B的层次结构。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章