python - 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
在子类中,我们在母亲之前先上了父亲类,那么父亲不应该在母亲之前打印吗?这个序列背后有什么逻辑吗?
解决方案
您可以随时咨询__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
再次进入之后。
在现实生活用例中,不建议过度使用多重继承。这可能是一个巨大的痛苦。组合和混合更容易理解。
推荐阅读
- javascript - 在 Firebase 中使用 async/await 时,我是否必须使用 .then
- sql-server - 为什么 Access 不断恢复到旧版本的链接 SQL Server 表?
- mongodb - 从旧的 mongo 恢复转储
- python - Psycopg2 Postgres Unnesting a very long array to insert it into a tables column
- python - 用新值替换 Python 字典值
- python - 剥离lxml中的单个元素
- python - 在运行 jupyter 的 Google Cloud VM 中导入必要的库时遇到问题
- html - 如何使另一张幻灯片图像出现?
- flutter - 在 setState() 中调用 Provider 自定义方法导致错误:或在构建期间调用 markNeedsBuild()
- python - 如何将一个函数的结果存储到一个类中?