问题
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