首页 > 解决方案 > 学习继承时的意外结果

问题描述

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

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 to MRO),然后super().test()从 B 类调用,它将打印 test of A called.

我在这里错在哪里?

标签: pythonoopinheritance

解决方案


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


推荐阅读