【问题标题】:Unexpected results when learning about inheritance学习继承时的意外结果
【发布时间】:2020-12-28 05:27:03
【问题描述】:

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

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

我哪里错了?

【问题讨论】:

标签: python oop inheritance


【解决方案1】:

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

【讨论】:

  • 这意味着首先调用classB,然后根据MRO调用classC,然后classC使用super,所以会调用A类对吗?
  • 是的。我不知道确切的 MRO 规则,但基本上如果层次结构中的两个类有一个公共基类,MRO 将把这个公共基类保存到最后。
  • 明白,感谢您的回答。我已接受并投了赞成票。
【解决方案2】:

将您的代码逐行粘贴到 [http://pythontutor.com/visualize.html][1] 和 Visulize 中。我希望它的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 2014-09-04
    • 2018-11-03
    • 2011-01-23
    相关资源
    最近更新 更多