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