9

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.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
qdet
  • 115
  • 3
  • Does this answer your question? [What does 'super' do in Python?](https://stackoverflow.com/questions/222877/what-does-super-do-in-python) – Rabbid76 May 28 '21 at 18:25

1 Answers1

4

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.

  • 1
    As always, the most baffling issues turn out to have the simplest explanations. Thanks for the clear, concise answer! – qdet Dec 19 '14 at 12:56