python - 多重继承和超级
问题描述
为什么这仅在我config
从__init__
in 中删除时才有效Second
?
class First(object):
def __init__(self, config):
super().__init__(config)
print("first", config)
class Second(object):
def __init__(self, config): # <-- works only if I remove config
super().__init__(config)
print("second", config)
class Third(First, Second):
def __init__(self, config):
super().__init__(config)
print("third", config)
Third({"name": "alex"})
=> second {'name': 'alex'}
=> first {'name': 'alex'}
=> third {'name': 'alex'}
解决方案
错误消息告诉您究竟出了什么问题:
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
Second
的父类是object
,并且您使用__init__
额外的参数调用它。
super()
只给你第一个父类,这使得当你进行多重继承时它通常没有帮助(而且经常只是令人困惑)。如果您修复代码以消除调用错误,object.__init__(config)
您会得到:
class First: # note that in modern Python you don't need to give object as the parent
def __init__(self, config):
print("first", config)
class Second:
def __init__(self, config):
print("second", config)
class Third(First, Second):
def __init__(self, config):
super().__init__(config)
print("third", config)
Third({"name": "alex"})
first {'name': 'alex'}
third {'name': 'alex'}
因为你的super().__init__
电话只有电话First
。相反,您可能希望显式调用每个父类的构造函数:
class Third(First, Second):
def __init__(self, config):
First.__init__(self, config)
Second.__init__(self, config)
print("third", config)
first {'name': 'alex'}
second {'name': 'alex'}
third {'name': 'alex'}
推荐阅读
- java - 给定团队规模和团队成员限制,找出所有可能的团队组合
- bash - 如何使用bash脚本从文件中的字符串中获取具有可变位数的数字?
- html - 使用 CSS 的淡入和淡出效果有问题
- python - Selenium 不会打开特定的 chrome 配置文件 python
- python - 如何在 Kaggle 笔记本中编写 TFRecords?
- netbeans - 具有并行测试的 Netbeans 12 和 TestNG
- c++ - 是否可以覆盖 C++ 中的运算符?如果答案是肯定的,范围是多少?
- wordpress - 在 H2 标题前插入 1、2、3... 数字
- python - 运行for循环两次后如何打印i?
- reactjs - 尝试使用 React Bootstrap 分页显示数组中的项目