Python中的super().__ init __()和显式超类__init __()之间的行为差​​异

qde*_*det 7 inheritance super keyword-argument python-3.x

super().__init__()在代码中使用和显式调用超类构造函数之间的行为有一个无法解释的差异.

class IPElement(object):

def __init__(self, ip_type='IPv4'):
    self.ip_type = ip_type

class IPAddressSimple(IPElement):

    def __init__(self, ip_name, ip_type='IPv4'):
        self.ip_name = ip_name
        super().__init__(self, ip_type=ip_type)
Run Code Online (Sandbox Code Playgroud)

这里,该行super().__init__(self, ip_type=ip_type)导致类型错误:

TypeError: __init__() got multiple values for argument 'ip_type'
Run Code Online (Sandbox Code Playgroud)

当我将调用更改为ip_type按位置传递时(例如,super().__init__(self, ip_type)我得到一个不同的类型错误:

TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given
Run Code Online (Sandbox Code Playgroud)

这些错误都没有对我有意义,当我用super()超类的显式名称替换时,一切都按预期工作.以下工作正常,就像按位置传递ip_type一样:

class IPAddressSimple(IPElement):

        def __init__(self, ip_name, ip_type='IPv4'):
            self.ip_name = ip_name
            IPElement.__init__(self, ip_type=ip_type)
Run Code Online (Sandbox Code Playgroud)

__init__如果有必要,我当然可以使用显式调用超类方法,但我想理解为什么super()不在这里工作.

小智 4

super()已经self为你传递了。super(IPAddressSimple)不会知道self,所以在这种情况下你需要打电话super(IPAddressSimple).__init__(self, ip_type)。但是super()( 这是 的语法糖super(IPAddressSimple, self)) 知道self并处理它,所以你应该只ip_type手动传递。