Python inheritance with super(), overriding and the MRO, one line at a time.
In one line
A new class (the child) takes over the attributes and methods of an existing class (the parent) and adds or changes only what is different. You write the parent in parentheses: class Truck(Vehicle):.
Why you need it
If bicycles, trucks and buses all have a name, a wheel count, a distance and drive(), you end up copying the same code into three classes. Fix the distance logic in two of them and forget the third, and the results drift apart.
Keep the shared part once in Vehicle and let each child state only its differences. There is one place to fix.
Everyday picture
Think of a franchise. Head office writes the manual (the parent) for checkout, cleaning and greetings. Each branch (a child) follows it and adds a local dish or two. When head office changes a rule, every branch picks it up at once.
Example code
main.py · 40 lines
classVehicle:def__init__(self, name, wheels):self.name = nameself.wheels = wheelsself.km = 0defdrive(self, km):self.km += kmreturnf"{self.name} drove {km}km (total {self.km}km)"defdescribe(self):returnf"{self.name} on {self.wheels} wheels"classBicycle(Vehicle):def__init__(self, name):super().__init__(name, 2)defring(self):returnf"{self.name}: ring ring"classTruck(Vehicle):def__init__(self, name, load_limit):super().__init__(name, 6)self.load_limit = load_limitdefdescribe(self): base = super().describe()returnf"{base}, carries up to {self.load_limit}kg"bike = Bicycle("Pedal")truck = Truck("Hauler", 1000)print(bike.drive(5))print(truck.drive(40))print(bike.describe())print(truck.describe())print(bike.ring())print(isinstance(truck, Vehicle), Truck.__mro__[1].__name__)
Press Run to try your edited code right away. The step-through and the output above follow the original code.
When to use it
An "is a" sentence sounds right: a truck is a vehicle
Several classes share many attributes and methods
Each child should do a parent method a little differently (overriding)
If "has a" fits better (a robot has a battery), use composition instead. It comes two topics later.
Python allows several parents (multiple inheritance). Check the lookup order with ClassName.__mro__.
Common mistakes
Leaving out super().__init__() in the child
Once the child writes its own __init__, the parent one no longer runs by itself. name and km never get set, so reading them fails.
Code that calls it the parent way (v.drive(10)) breaks on the child. Give new parameters a default so the parent-style call still works.
Wrong
classVehicle:defdrive(self, km):return kmclassTruck(Vehicle):defdrive(self, km, load):return km * 2if load else kmfor v in [Vehicle(), Truck()]:print(v.drive(10))
When you run itTypeError: Truck.drive() missing 1 required positional argument: 'load'
Fixed
classVehicle:defdrive(self, km):return kmclassTruck(Vehicle):defdrive(self, km, load=0):return km * 2if load else kmfor v in [Vehicle(), Truck()]:print(v.drive(10))
When you run it10
10
Calling the parent method through the class without self
Vehicle.describe() called on the class has no object to work on. super().describe() passes the current object for you.
Wrong
classVehicle:defdescribe(self):return"a vehicle"classTruck(Vehicle):defdescribe(self):returnVehicle.describe() + " that carries cargo"print(Truck().describe())
When you run itTypeError: Vehicle.describe() missing 1 required positional argument: 'self'
Fixed
classVehicle:defdescribe(self):return"a vehicle"classTruck(Vehicle):defdescribe(self):returnsuper().describe() + " that carries cargo"print(Truck().describe())
When you run ita vehicle that carries cargo
Check yourself
Question 1
What does Truck("Mule", 500).describe() return?
t = Truck("Mule", 500)print(t.describe())
Show the answer
Answer: 2. Mule on 6 wheels, carries up to 500kg The truck's own describe runs. It gets the parent sentence with super().describe() and appends the load limit.
Question 2
When you call bike.describe(), which class does Python search first?
print([c.__name__ for c inBicycle.__mro__])
Show the answer
Answer: 2. Bicycle The order is Bicycle, then Vehicle, then object. Bicycle has no describe, so the one in Vehicle is used.
Questions people ask
Why use super()?
It calls the parent class method on the current object. The most common case is super().__init__(...) in a child __init__, so the parent sets its values first.
Can a class have several parents?
Yes, as in class C(A, B):. Check the lookup order with C.__mro__; super() follows that order too.
How do I choose between inheritance and composition?
If "a truck is a vehicle" sounds right, inherit. If "a robot has a battery" fits better, use composition.