多重继承和超级

时间:2021-01-30 21:31:49

标签: python

为什么这仅在我从 config 中的 __init__ 中删除 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'}

1 个答案:

答案 0 :(得分:0)

错误消息会准确地告诉您出了什么问题:

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'}