gpt4 book ai didi

python - Python 中 super().__init__() 和显式父类(super class) __init__() 之间的行为差​​异

转载 作者:行者123 更新时间:2023-12-04 02:43:38 24 4
gpt4 key购买 nike

我在使用 super().__init__() 之间发现了无法解释的行为差异并在我的代码中显式调用父类(super class)构造函数。

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)

在这里,行 super().__init__(self, ip_type=ip_type)导致类型错误:
TypeError: __init__() got multiple values for argument 'ip_type'

当我将调用更改为通过 ip_type按位置(例如 super().__init__(self, ip_type) 我收到不同类型的错误:
TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given

这些错误对我来说都没有意义,当我替换 super() 时使用父类(super class)的显式名称,一切都按预期工作。以下工作正常,按位置传递 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)

我当然可以使用显式调用父类(super class) __init__必要时的方法,但我想了解为什么 super()不在这里工作。

最佳答案

super()已经通过 self陪着你。 super(IPAddressSimple)不会知道 self ,因此在这种情况下,您需要调用 super(IPAddressSimple).__init__(self, ip_type) .但是super() (这是 super(IPAddressSimple, self) 的语法糖)知道 self并处理它,所以你应该只通过 ip_type手动。

关于python - Python 中 super().__init__() 和显式父类(super class) __init__() 之间的行为差​​异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27566391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com