为什么没有被称为"在这个例子中打印两次?

时间:2017-09-27 18:49:42

标签: python python-3.x

我来自https://www.python-course.eu/python3_multiple_inheritance.php

class A:
    def m(self):
        print("m of A called")

class B(A):
    def m(self):
        print("m of B called")
        super().m()

class C(A):
    def m(self):
        print("m of C called")
        super().m()

class D(B, C):
    def m(self):
        print("m of D called")
        super().m()

输出:

>>> from super5 import D
>>> x = D()
>>> x.m()
m of D called
m of B called
m of C called
m of A called

我是编程的初学者,我很难理解super()和MRO是如何工作的。对不起,如果这是一个愚蠢的问题。

1 个答案:

答案 0 :(得分:1)

super确保您遵循方法解析顺序。因此,如果每个类包含一个(正确的)super,它将遵循您最初调用该方法的类的MRO。

在您的情况下,它是D的实例,而D的MRO是:

>>> D.mro()
[D, B, C, A, object]

所以它首先会使用调用super的D.m进入B.m,而C.m依次调用super,A.m使用super然后调用A。但是,由于super未使用object.m,所以它会停止 - 因此它不会尝试调用A

由于super在MRO中不存在两次(不确定是否可能),因此没有理由期望它被调用两次。至少不是你只使用paste0("ggplot(data=TP, aes(Date)) + ", gl, "labs(x='', y='Balances ($B)')") s。

如果您想知道MRO是如何创建的,那么它就是official documentation。简而言之:在调用父项之前调用兄弟姐妹(具有相同父项的子类),但仅仅因为父项具有多个子项并不意味着它被多次调用。