python - Python 中的混合继承

标签 python oop inheritance

我正在尝试在 python 中实现多重混合继承,它也给出了答案,但我想知道这个代码的答案序列背后的原因是什么:

class GrandPa:
    def __init__(self):
        print("Grand Pa")

class Father(GrandPa):
    def __init__(self):
        super().__init__()
        print("Father")

class Mother(GrandPa):
    def __init__(self):
        super().__init__()
        print("Mother")


class child(Father, Mother):
    def __init__(self):
        super().__init__()
        print("Child")

c = child()

输出

Grand Pa
Mother
Father
Child

在子类中,我们在母亲之前使用了Father类,所以Father不应该在Mother之前打印吗?这个序列背后有什么逻辑吗?

最佳答案

您可以随时咨询__mro__了解发生了什么:

print(c.__class__.__mro__)
# (<class '__main__.child'>, <class '__main__.Father'>, <class '__main__.Mother'>, <class '__main__.GrandPa'>, <class 'object'>)

事实上,在这条链中,父亲先于母亲出现。

但是,当您像这样链接调用时,实际发生的情况是:

class GrandPa:
    def __init__(self):
        print("Grand Pa")

class Father(GrandPa):
    def __init__(self):
        print('f', super())
        super().__init__()
        print("Father")

class Mother(GrandPa):
    def __init__(self):
        print('m', super())
        super().__init__()
        print("Mother")


class child(Father, Mother):
    def __init__(self):
        print('c', super())
        super().__init__()
        print("Child")

c = child()

我已将 print(super()) 添加到所有方法中,以说明调用堆栈内发生的情况:

c <super: <class 'child'>, <child object>>
f <super: <class 'Father'>, <child object>>
m <super: <class 'Mother'>, <child object>>
Grand Pa
Mother
Father
Child

正如你所看到的,我们从Child开始,然后转到Father,然后到Mother,只有在之后>GrandPa 被执行。然后控制流返回到Mother,并且只有在再次返回到Father之后。

在现实生活中的用例中,不建议过度使用多重继承。这可能是一个巨大的痛苦。组合和 mixin 更容易理解。

关于python - Python 中的混合继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62895004/

相关文章:

c++ - 如何将 DRY 原则应用于 C++ 中的迭代器? (迭代器、const_iterator、reverse_iterator、const_reverse_iterator)

python - 使用 Pandas 计算并绘制计数比率

python - Numpy 张量 : Tensordot over frontal slices of tensor

php - 拆分包含的函数会提高 PHP 性能吗?

flash - 如何在AS3中定义具有不同参数的接口(interface)方法?

c++ - 自定义派生的 std::exception 类的 'what' 函数返回神秘的废话

javascript - 创建一个从 ES6 Map 扩展的类

javascript - 如何在 python 应用程序中高效地提供 JS 和 CSS

python - 在 CSV 文件中使用 random.choice 打印相邻单元格

java - 实现接口(interface)和对象