Python's super() , what exactly happens?
This question already has an answer here:
__init__
isn't a constructor, it's an initializer . By the time __init__
is called, the objects has already been constructed (via __new__
). So you get only one object, but it's initialized twice - for example, ElectricCar.__init__
may decide to re-initialize self.model
after Car.__init__
has been run.
When calling super()
, the appropriate baseclass is looked up in the context of the current instance. Basically, super().__init__(make, model, year)
could be rewritten as Car.__init__(self, make, model, year)
in your example.
This is why in earlier versions of python, the call was actually super(ElectricCar, self)
- it looks up the baseclass of the current class ( ElectricCar
) and uses the current instance ( self
) as if it were an instance of that class instead.
Note that initializing doesn't mean preparing the object, it means preparing the object's state. An object is fully functional even when it does not implement __init__
.
To clarify: When you call ElectricCar()
, what is actually executed is close to this:
that_object = ElectricCar.__new__() # this will actually use object.__new__
if isinstance(that_object, ElectricCar):
ElectricCar.__init__(that_object)
return that_object
That means you have one object from the call to ElectricCar.__new__
. The call to ElectricCar.__init__
will only modify/initialize that object. It may do so using other functions, such as Car.__init__
.