为什么这只在我从Second中的__init__中删除config时才起作用
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'}发布于 2021-01-31 05:43:29
错误消息准确地告诉您出了什么问题:
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'}https://stackoverflow.com/questions/65973324
复制相似问题