小编qde*_*det的帖子

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

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()不在这里工作.

inheritance super keyword-argument python-3.x

7
推荐指数
1
解决办法
517
查看次数

标签 统计

inheritance ×1

keyword-argument ×1

python-3.x ×1

super ×1