首页 > 解决方案 > 多重继承和超级

问题描述

为什么这仅在我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'}

标签: python

解决方案


错误消息告诉您究竟出了什么问题:

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

推荐阅读