我在使用 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/