python - 在 Python 3+ 多继承中使用 super 来初始化带参数的父类
问题描述
我知道它是如何工作的,它从MRO以前super
的基类中找到方法。
因此,如果我有两个基类和,并让它们继承,我应该如何使用来初始化以及它们是否需要参数?像这样: A
B
class C
super
A
B
class A:
def __init__(self, a):
self.a = a
class B:
def __init__(self, b):
self.b = b
class C(A, B): # inherit from A and B
def __init__(self, c):
A.__init__(self, a=1)
B.__init__(self, b=2) # How to use super here?
self.c = c
如果我super
在 each中使用class
,我需要确保正确的继承顺序:
class A:
def __init__(self, a):
super().__init__(b=3)
self.a = a
class B:
def __init__(self, b):
super().__init__()
self.b = b
class C(A, B): # Here must be (A, B)
def __init__(self, c, a):
super().__init__(a=a)
self.c = c
但这使得A
和B
耦合,这真的很糟糕。我应该如何处理这种情况,即B
初始化C
?不使用super
?最Pythonic的方式是什么?
解决方案
推荐阅读
- java - 可迭代对象的迭代器应在 Java 中返回可迭代对象本身
- javascript - 如何等待按钮启用并使用 puppeteer 单击?
- postgresql - 错误:在 Alpine Docker 映像上安装 PostGIS 时出现无法满足的约束
- python - 为什么我不能覆盖使用 `dataclasses_json` 的 `dataclass` 对象的 `to_dict` 方法?
- python - 用于列计算的 for 循环
- mysql - 如何在 debian buster 中安装 mysql 工作台?
- javascript - 将状态传递给history.push时反应路由器无法按预期工作
- c# - 检查至少一个对象是否不为零
- c# - 升级 MsBuild 版本后 Xamarin Forms Android Linker 问题
- uwp - 新证书后无法更新 UWP 应用