【问题标题】:Hybrid Inheritance in PythonPython中的混合继承
【发布时间】:2020-07-14 12:17:04
【问题描述】:

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

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

【问题讨论】:

标签: python oop inheritance


【解决方案1】:

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

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

事实上,Father 在这条链中排在 Mother 之前。

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

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之后。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 2020-10-17
    • 2010-11-21
    • 2015-07-03
    • 1970-01-01
    • 2011-11-12
    相关资源
    最近更新 更多