Python中的super().__ init __()和显式超类__init __()之间的行为差异 [英] Behavior difference between super().__init__() and explicit superclass __init__() in Python
问题描述
我在使用 super().__ init __()
和在我的代码中显式调用超类构造函数之间的行为方面存在无法解释的差异。
I am getting an unexplained difference in behavior between using super().__init__()
and explicitly calling a super class constructor in my code.
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)
导致类型错误:
Here, the line super().__init__(self, ip_type=ip_type)
results in a type error:
TypeError: __init__() got multiple values for argument 'ip_type'
当我将呼叫更改为按位置传递 ip_type
(例如 super().__ init __(self,ip_type)
我收到不同的类型错误:
When I change the call to pass ip_type
by position (e.g. super().__init__(self, ip_type)
I get a different type error:
TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given
这些错误都没有意义,当我更换 super( )
使用超类的显式名称,一切都按预期工作。以下工作正常,就像通过位置传递ip_type一样:
Neither of these errors makes sense to me, and when I replace super()
with the explicit name of the superclass, everything works as expected. The following works just fine, as does passing ip_type by position:
class IPAddressSimple(IPElement):
def __init__(self, ip_name, ip_type='IPv4'):
self.ip_name = ip_name
IPElement.__init__(self, ip_type=ip_type)
如果有必要,我当然可以使用显式调用超类 __ init __
方法,但我想理解为什么 super()
在这里不起作用。
I can certainly use an explicit call to the superclass __init__
method if necessary, but I would like to understand why super()
is not working here.
推荐答案
super()
已为您传递 self
。 super(IPAddressSimple)
不知道 self
,所以在这种情况下你需要调用 super(IPAddressSimple).__ init __(self,ip_type)
。但是 super()
(这是 super(IPAddressSimple,self)
的语法糖)知道自我
并处理它,所以你只能手动传递 ip_type
。
super()
already passes self
along for you. super(IPAddressSimple)
would not know about self
, so in that case you'd need to call super(IPAddressSimple).__init__(self, ip_type)
. But super()
(which is syntactic sugar for super(IPAddressSimple, self)
) knows self
and handles it, so you should only pass ip_type
manually.
这篇关于Python中的super().__ init __()和显式超类__init __()之间的行为差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!