Before you start
Inheritance is easy to misuse. This lesson teaches HOW to use it correctly. The NEXT lesson (composition vs inheritance) teaches WHEN NOT to reach for it.
The one-line version
Inheritance lets a child class reuse the parent's data and methods, and change what it needs to.
Why every design problem needs this
Almost every design problem you'll see has a hierarchy in it:
- Parking Lot — Vehicle parent, Car / Bike / Truck children with different spot sizes and fees.
- Vending Machine — Product parent, Snack / Beverage children with different rules.
- Chess — Piece parent, Pawn / Knight / Bishop / etc. children with different movement rules.
- File System — Node parent, File / Directory children that behave differently.
Every one of these problems asks you to write a method (like
price() or move()) once on the parent class, then let
children replace it. Other code holds a list[Vehicle] and
doesn't care which kind of vehicle is inside.
That's called "polymorphism" — you'll meet the word in
lesson 5. You're already using it every time you loop
through a mixed list of vehicles and call .describe().
What super() does
Two things:
In
__init__, it calls the parent's setup function. Without this call, the parent's setup code never runs. That meansself.plateandself.wheelsnever get stored. Every downstream test breaks.In an override, it lets you REUSE what the parent did.
super().describe()runs the parent's version. You can add to the result instead of writing the whole thing from scratch.
If you never call super(), you're probably better off with
composition (next lesson).
What NOT to do with inheritance
Books have entire chapters on this. Short version:
- Don't use inheritance just to reuse code. If Truck doesn't behave like a Vehicle, don't make it a child of Vehicle just to borrow Vehicle's methods. Use composition.
- Don't build deep hierarchies. More than 2-3 levels is usually a sign something's wrong. Interviewers notice.
- Watch out for "fragile base class". When you change the parent, all the children might break in ways you didn't expect.
We'll draw the line in the next lesson. For today, just get
comfortable with super(), class Child(Parent):, and
overriding methods.