Inheritance & Polymorphism
Every class so far has stood alone. Chapter 15's Account class never shared code with any other class, even though a real bank actually has several kinds of accounts — a checking account, a savings account, a business account — that are all clearly "accounts," but each with its own twist. This chapter finally lets one class build directly on another, so that shared behavior is written once, and each subclass only adds or changes what makes it different.
How to read this chapter
- Inheritance is a "is-a" relationship. A
Caris aVehicle, plus some extra car-specific details. That phrase is the test for whether inheritance is the right tool at all. - Sub-topics build in order: basic inheritance first, then reusing the parent's setup, then changing behavior, and finally the payoff — polymorphism, where different subclasses respond to the same method call each in their own way.
- Everything from Chapters 1-15 still applies inside every class in this chapter —
__init__, instance/class attributes, dunder methods,@property, all of it. Inheritance andsuper()are the only genuinely new ingredients.
make/model setup, and a giant if vehicle_type == "car": ... elif vehicle_type == "motorcycle": ... chain anywhere the app needs to display one. This chapter's tools — inheritance and polymorphism — are exactly how real production code avoids both problems at once.
1. Basic inheritance
- A subclass is written as
class Child(Parent):, with the parent class's name in parentheses. - A subclass automatically gets every attribute and method the parent class defines — nothing needs to be retyped.
- An empty subclass body, just
pass, is already a fully working class that behaves exactly like its parent.
A Vehicle class stores what every vehicle has in common:
class Child(Parent):.
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def describe(self):
return f"{self.make} {self.model}"
class Car(Vehicle):
pass
car = Car("Toyota", "Corolla")
print(car.describe())
print(car.make, car.model)
Toyota Corolla
Toyota Corolla
Thought process: the point of this example is proving the "is-a" claim with the smallest possible subclass — an empty body — so the demo has to call both a method defined only on the parent (describe()) and access an attribute set only by the parent's __init__ (make/model), otherwise "it inherits everything automatically" would just be an assertion rather than something the reader watches happen.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write a Python class Vehicle with __init__(self, make, model) that stores self.make and self.model, and a describe(self) method returning f"{self.make} {self.model}". Then write a class Car(Vehicle) with an empty body (just `pass`) — no __init__, no methods of its own. Create a Car with make="Toyota", model="Corolla" and print car.describe() and car.make, car.model, proving both the inherited method and the inherited attributes work without Car redefining anything.
Car(Vehicle) means "Car is a
Vehicle, plus whatever Car adds." The
body is just pass — no new code at all — yet
car.describe() and car.make both work.
Python looks up describe on Car first,
doesn't find it there, then checks Vehicle and finds
it — this lookup chain is exactly what "inherits automatically"
means.
Vehicle is the
parent; Car is the subclass.
A subclass isn't limited to an empty body — it can also add brand-new methods that only it has, on top of everything it already inherited:
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def describe(self):
return f"{self.make} {self.model}"
class Car(Vehicle):
def honk(self):
return "Beep beep!"
car = Car("Honda", "Civic")
print(car.describe())
print(car.honk())
Honda Civic
Beep beep!
Thought process: the previous example already proved a subclass gets a parent's methods for free — this one needs to prove the reverse direction just as clearly: a method added only to the subclass, so calling car.honk() works but would fail on a plain Vehicle object, showing inheritance is one-directional rather than a two-way merge.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Using the same Vehicle class (with __init__(self, make, model) and describe(self)), write a Car(Vehicle) subclass that adds one new method, honk(self), returning "Beep beep!" — a method Vehicle itself does not have. Create a Car with make="Honda", model="Civic" and call both car.describe() (inherited) and car.honk() (Car-only) to show both work. Add a one-line comment noting that a plain Vehicle instance would raise AttributeError if .honk() were called on it.
honk exists only on Car — a plain
Vehicle object would have no honk()
method at all. Inheritance flows one direction: a subclass gains
everything its parent has, but a parent knows nothing about what
any of its subclasses might add later.
Go Deeper: every class already inherits from something
Even a class written as class Vehicle:, with no
parentheses at all, secretly inherits from Python's built-in
base class, object. That's where dunder methods
like a default __eq__ or __repr__
actually come from before a class overrides them — inheritance
has quietly been part of every class since Chapter 14.
class Child(Parent):makesChilda subclass ofParent.- A subclass automatically gets every attribute and method its parent defines, with no retyping.
- A subclass can also add its own new methods that the parent doesn't have.
2. super().__init__()
super().__init__(...)calls the parent class's__init__from inside the child's own__init__.- It reuses the parent's setup instead of duplicating those same lines of code in every subclass.
- After calling
super().__init__(...), the child's__init__can go on to set its own extra attributes.
Car never defined its own __init__ at all. A subclass that needs one extra attribute, like a car's number of doors, needs its own __init__ — and super() is how it avoids retyping the parent's setup to get there.
A plain Car needs everything Vehicle
already sets up, plus one extra detail of its own:
super()?
super() gives access to the parent class from
inside a subclass, most often to call one of the parent's
methods. super().__init__(...) specifically calls
the parent class's __init__, passing along whatever
arguments it needs.
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def describe(self):
return f"{self.make} {self.model}"
class Car(Vehicle):
def __init__(self, make, model, num_doors):
super().__init__(make, model)
self.num_doors = num_doors
car = Car("Toyota", "Corolla", 4)
print(car.describe())
print(car.make, car.num_doors)
Toyota Corolla
Toyota 4
super().__init__(make, model) runs
Vehicle's __init__ exactly as if it had
been called directly, setting self.make and
self.model. The line right after it,
self.num_doors = num_doors, then adds the one thing
that's specific to a Car — everything shared lives
in Vehicle, and everything car-specific lives in
Car.
Compare that to skipping super() and duplicating the
parent's setup by hand instead:
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
class Car(Vehicle):
def __init__(self, make, model, num_doors):
self.make = make
self.model = model
self.num_doors = num_doors
car = Car("Honda", "Civic", 4)
print(car.make, car.model, car.num_doors)
Honda Civic 4
Both versions print the same thing today. But if
Vehicle.__init__ later added validation, like
rejecting a blank make, the duplicated version in
Car would silently miss that fix — super()
keeps every subclass automatically in sync with whatever the
parent's setup actually does, now and later.
Go Deeper: what if the child defines no __init__ at all?
Sub-topic 1's Car(Vehicle): pass never needed
super().__init__() at all — with no
__init__ of its own, Python automatically uses the
parent's __init__ unchanged. super()
only becomes necessary once the child defines its own
__init__ and still wants the parent's setup to run
too.
super().__init__(...)calls the parent's__init__from inside the child's own__init__.- It reuses the parent's setup instead of duplicating those lines in every subclass.
- The child's
__init__can add its own extra attributes right after callingsuper().__init__(...).
3. Method overriding
- Overriding means a subclass defines a method with the exact same name as one on its parent, replacing that behavior for the subclass.
- An override can fully replace the parent's version, or call
super().method()from inside itself to build on top of it instead. - Overriding is what lets each subclass genuinely behave differently while still sharing the same method name.
describe() works fine for any Vehicle, but a Car can describe itself more specifically. Overriding is how a subclass says "use my version of this method instead."
Giving Car its own describe method,
with the same name as Vehicle's, replaces it:
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def describe(self):
return f"{self.make} {self.model}"
class Car(Vehicle):
def __init__(self, make, model, num_doors):
super().__init__(make, model)
self.num_doors = num_doors
def describe(self):
return f"{self.make} {self.model} ({self.num_doors}-door sedan)"
vehicle = Vehicle("Generic", "Transport")
car = Car("Toyota", "Corolla", 4)
print(vehicle.describe())
print(car.describe())
Generic Transport
Toyota Corolla (4-door sedan)
Both classes have a method named describe, but each
object runs its own class's version — vehicle.describe()
uses Vehicle's, and car.describe() uses
Car's completely separate one. Nothing about
Vehicle's version changed; Car simply
supplied a replacement for itself.
Sometimes a subclass doesn't want to fully replace the parent's
behavior — just extend it. Calling super().describe()
from inside the override runs the parent's version first, then
adds more on top:
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def describe(self):
return f"{self.make} {self.model}"
class Car(Vehicle):
def __init__(self, make, model, num_doors):
super().__init__(make, model)
self.num_doors = num_doors
def describe(self):
base = super().describe()
return f"{base} — {self.num_doors}-door car"
car = Car("Toyota", "Corolla", 4)
print(car.describe())
Toyota Corolla — 4-door car
super().describe() inside Car's
override calls Vehicle's original
describe(), returning "Toyota Corolla"
into the local variable base. Car's
version then builds on that result instead of retyping
f"{self.make} {self.model}" all over again — the
same "reuse instead of duplicate" idea super().__init__()
already used for setup, now applied to any method.
Go Deeper: overriding __init__ vs overriding any other method
Sub-topic 2's super().__init__(...) is really the
exact same idea as this sub-topic's super().describe()
— __init__ is just a method like any other, and
it's just as overridable. There's nothing special about it
needing its own separate rule.
- A subclass overrides a parent's method by defining a new method with the exact same name.
- An override can fully replace the parent's behavior, or call
super().method()to build on top of it. - Each object always runs its own class's version of an overridden method.
4. Polymorphism
- Polymorphism means different subclasses respond to the exact same method call, each in their own way.
- Looping over a list of different subclass objects and calling the same method name on each gets different, correct output per type — automatically.
- No
if/elifchain checking each object's type is needed at all; overriding already handles it.
Car overriding describe(). Polymorphism is what happens when a whole list mixes several different subclasses together, and the exact same one line of calling code just works for all of them.
Three different vehicle subclasses, each overriding
describe() in their own way:
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def describe(self):
return f"{self.make} {self.model} is a generic vehicle."
class Car(Vehicle):
def describe(self):
return f"{self.make} {self.model} is a car built for the road."
class Motorcycle(Vehicle):
def describe(self):
return f"{self.make} {self.model} is a motorcycle built for speed."
class Truck(Vehicle):
def describe(self):
return f"{self.make} {self.model} is a truck built to haul cargo."
vehicles = [
Car("Toyota", "Corolla"),
Motorcycle("Harley-Davidson", "Iron 883"),
Truck("Ford", "F-150"),
]
for vehicle in vehicles:
print(vehicle.describe())
Toyota Corolla is a car built for the road.
Harley-Davidson Iron 883 is a motorcycle built for speed.
Ford F-150 is a truck built to haul cargo.
The loop body is just print(vehicle.describe()) —
one line, run three times, with no
if isinstance(vehicle, Car): ... elif ... anywhere
in sight. Each object already "knows" which describe()
to run, because that decision was already made once, correctly,
back when each subclass overrode the method.
This is the direct payoff of Sub-topic 3: overriding is what makes each class's behavior different, and polymorphism is what that difference looks like from the outside, at the exact moment the same method call is used across a mixed list of types.
Go Deeper: the same idea works without inheritance too
Python's polymorphism is actually looser than some other languages' — any two classes with a method of the same name can be swapped in a loop like this, even without sharing a common parent (this is often called "duck typing": if it walks like a duck and quacks like a duck...). This chapter focuses on the inheritance-based version, since that's the far more common and predictable pattern in real codebases.
- Polymorphism: different subclasses respond to the same method call, each in their own way.
- Looping over mixed subclass objects and calling one shared method name just works — no type-checking needed.
- Overriding (Sub-topic 3) is what makes each subclass's response different in the first place.
5. isinstance() vs type()
isinstance(obj, SomeClass)checks whetherobjis that class or any subclass of it.type(obj) == SomeClasschecks for an exact class match only, ignoring the inheritance relationship entirely.isinstance()is usually the right choice, since aCargenuinely still is aVehicle.
A Car object satisfies both "is it a Car?"
and "is it a Vehicle?" — but not "is it a
Motorcycle?":
isinstance()?
isinstance(obj, SomeClass) returns True
if obj is an object of SomeClass, or of
any class that inherits from SomeClass. It respects
the full inheritance relationship, not just an exact class match.
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
class Car(Vehicle):
pass
class Motorcycle(Vehicle):
pass
car = Car("Toyota", "Corolla")
print(isinstance(car, Car))
print(isinstance(car, Vehicle))
print(isinstance(car, Motorcycle))
print(type(car) == Car)
print(type(car) == Vehicle)
True
True
False
True
False
isinstance(car, Vehicle) is True,
because Car inherits from Vehicle — a
Car genuinely still counts as a Vehicle.
But type(car) == Vehicle is False,
because type(car) is exactly Car, never
Vehicle, even though Car is built on
top of it.
type() for class checking?
type(obj) == SomeClass checks whether
obj's class is exactly
SomeClass — a subclass never counts as a match, even
though it inherits everything SomeClass has.
This difference matters most inside a function meant to accept any kind of vehicle:
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
class Car(Vehicle):
pass
def print_if_vehicle(obj):
if isinstance(obj, Vehicle):
print(f"{obj.make} {obj.model} is some kind of vehicle.")
else:
print("Not a vehicle.")
car = Car("Honda", "Civic")
print_if_vehicle(car)
print(type(car) == Vehicle)
print(isinstance(car, Vehicle))
Honda Civic is some kind of vehicle.
False
True
print_if_vehicle correctly recognizes the
Car object as a vehicle, because it uses
isinstance(). Had it used
type(obj) == Vehicle instead, every single subclass
— Car, Motorcycle, anything else built
later — would incorrectly fail the check, which is almost never
the intended behavior.
Go Deeper: isinstance() also accepts a tuple of classes
isinstance(amount, (int, float)) — the exact check
Chapter 15's is_valid_amount used — passes a tuple
of classes, returning True if the object matches
any one of them. The same tuple form works with custom classes
too: isinstance(obj, (Car, Motorcycle)).
isinstance(obj, SomeClass)isTrueforSomeClassand any of its subclasses.type(obj) == SomeClassonly matches the exact class, ignoring inheritance entirely.isinstance()is usually the right choice, since a subclass object genuinely still "is" its parent's type too.
6. Real-world inheritance & polymorphism in production
- Polymorphism is exactly why long
if/elifchains checking an object's type keep disappearing from mature codebases. - Inheritance,
super(), overriding, and polymorphism all combine naturally in one small family of classes. - Deep inheritance hierarchies aren't automatically good — sometimes composition (one object containing another) fits better than "is-a" does.
Car is a Vehicle) — not just because two classes happen to share a few fields.
This chapter's opening hook described three vehicle types needing shared setup and a rider-facing description. Here's the full picture, combining every sub-topic:
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def describe(self):
return f"{self.make} {self.model} is a generic vehicle."
def fuel_type(self):
return "unknown fuel"
class Car(Vehicle):
def describe(self):
base = super().describe()
return f"{base} It's a car that runs on {self.fuel_type()}."
def fuel_type(self):
return "gasoline"
class ElectricCar(Car):
def fuel_type(self):
return "electricity"
vehicles = [
Vehicle("Generic", "Transport"),
Car("Toyota", "Corolla"),
ElectricCar("Tesla", "Model 3"),
]
for vehicle in vehicles:
print(vehicle.describe())
if isinstance(vehicle, Car):
print(f" -> This is also a Car (isinstance check).")
Generic Transport is a generic vehicle.
Toyota Corolla is a generic vehicle. It's a car that runs on gasoline.
-> This is also a Car (isinstance check).
Tesla Model 3 is a generic vehicle. It's a car that runs on electricity.
-> This is also a Car (isinstance check).
ElectricCar inherits from Car, which
itself inherits from Vehicle — a chain two levels
deep. ElectricCar only overrides fuel_type(),
yet describe() (inherited from Car,
which itself calls super().describe() up to
Vehicle) automatically picks up that override
through self.fuel_type() — polymorphism reaching
through two layers of inheritance at once. And
isinstance(vehicle, Car) correctly recognizes the
ElectricCar object as a Car too, since
it inherits from it.
Notice the loop never checks
if type(vehicle) == Car or type(vehicle) == ElectricCar: ...
to decide how to describe each one — that entire chain of checks
is replaced by each subclass simply overriding the methods it
needs to. This is the concrete reason polymorphism replaces long
if/elif type-checking chains in real production
code: every time a new vehicle type gets added, the loop itself
never has to change.
- GUI frameworks model every on-screen element (buttons, checkboxes, sliders) as subclasses of one shared
Widgetbase class, calling the same.render()or.on_click()on any of them without ever checking which specific widget it is. - Game engines model player characters, enemies, and NPCs as subclasses of one shared base class, so a single main loop can call
.update()on every object in the scene regardless of type. - Payment processing systems model different payment methods (credit card, bank transfer, digital wallet) as subclasses sharing one
.charge()method, so checkout code stays identical no matter which payment method a customer picks.
SportsCar(Car(Vehicle)) that's really only reusing one small piece of Car is often better modeled with composition — giving SportsCar an engine attribute that's itself an object, rather than stretching the "is-a" chain further than it comfortably holds. Real codebases favor "prefer composition over inheritance" once a hierarchy gets more than two or three levels deep.
Go Deeper: what's still missing after this chapter?
Every subclass here still relies on Python correctly finding the right overridden method automatically. What happens when a class needs to inherit from two parents at once, or when a whole family of classes needs to guarantee every subclass implements a certain method — those are genuinely more advanced topics (multiple inheritance, abstract base classes) that build directly on everything in this chapter, saved for later in the course.
- Polymorphism is why long
if/eliftype-checking chains keep disappearing from mature, growing codebases. - Inheritance,
super(), overriding, and polymorphism combine naturally, even across multiple inheritance levels. - Deep inheritance hierarchies aren't automatically the right call — composition is sometimes the better fit.
- GUI frameworks, game engines, and payment systems all lean on polymorphism so that adding a new subclass never requires touching the code that already loops over and calls methods on existing objects.
isinstance()checks show up constantly in real codebases wherever a function needs to safely handle several related types — logging, error handling, and data validation all use this pattern.- Mature engineering teams treat "prefer composition over inheritance" as a genuine guideline, not a rule against inheritance altogether — inheritance is the right tool exactly when the "is-a" relationship truly holds.
Points to Remember
class Child(Parent):makesChilda subclass that automatically inherits every attribute and methodParentdefines.super().__init__(...), called from inside the child's own__init__, reuses the parent's setup instead of duplicating it — the child can then add its own extra attributes.- Overriding means a subclass defines a method with the same name as its parent's;
super().method()inside the override extends the parent's behavior instead of fully replacing it. - Polymorphism: different subclasses respond to the same method call, each in their own way — looping and calling one shared method name works with no type-checking needed.
isinstance(obj, SomeClass)respects inheritance (true for subclasses too);type(obj) == SomeClassonly matches the exact class —isinstance()is usually the right choice.- Polymorphism is why long
if/eliftype-checking chains disappear from real codebases — but a very deep inheritance hierarchy is a real smell; composition is sometimes the better fit.