Behavior difference between super().__init__() and explicit superclass __init__() in Python

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-23 05:41:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/27566391/behavior-difference-between-super-init-and-explicit-superclass-init

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!