What does super() do in Python, and why call super().__init__()?
super() returns a proxy that looks up methods on the next class in the MRO. Calling super().__init__() runs the parent's initialiser so the inherited setup is not skipped. If a child defines __init__ and does not call it, the parent's attributes are never created.
Explain it simply
A new employee joins a company. Before the department-specific training, HR does the common onboarding, such as ID card and email. super().__init__() is that common onboarding. If the department skips it, the employee has no ID card.
Example
class Vehicle:
def __init__(self, wheels):
self.wheels = wheels
class Car(Vehicle):
def __init__(self, brand):
super().__init__(4)
self.brand = brand
class Broken(Vehicle):
def __init__(self, brand):
self.brand = brand
car = Car("Tata")
print(car.wheels, car.brand) # Output: 4 Tata
b = Broken("Tata")
print(hasattr(b, "wheels")) # Output: FalseBroken replaced the parent's __init__ without calling it, so wheels was never set.
What to say in the interview
"super() gives access to the next class in the MRO, not necessarily the direct parent. I call super().__init__() in a subclass so the parent's setup runs, and I use super() instead of naming the parent class so multiple inheritance keeps working. Python 3 needs no arguments."
Common mistakes
- Forgetting to pass the arguments the parent's
__init__expects.