python super().__init__()参数,Python中的super().__ init __()和显式超类__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)

Here, the line super().__init__(self, ip_type=ip_type) results in a type error:

TypeError: __init__() got multiple values for argument '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

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)

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() 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值