首页 > 解决方案 > Python中的混合继承

问题描述

我正在尝试在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

在子类中,我们在母亲之前先上了父亲类,那么父亲不应该在母亲之前打印吗?这个序列背后有什么逻辑吗?

标签: pythonoopinheritance

解决方案


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

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

并且确实FatherMother在这个链条之前。

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

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再次进入之后。

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


推荐阅读