🐍 Python for Everyone

← Back to all chapters

Chapter 16 of 27 Intermediate 65 min read

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

Picture a ride-sharing app's backend modeling every vehicle on the road: cars, motorcycles, and delivery trucks. All three need a make, a model, and a way to describe themselves to a rider. Without inheritance, that means three separate classes, each retyping the exact same 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.
Sub-topic 1 of 6

1. Basic inheritance

At a glance
  • 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.
Why this matters: real systems always have families of related things — vehicles, employees, shapes, accounts. Inheritance is how code expresses "this new thing is a specific kind of that existing thing," instead of writing every kind from scratch.

A Vehicle class stores what every vehicle has in common:

What is... inheritance? Inheritance lets one class (the subclass, or "child") automatically receive all the attributes and methods of another class (the parent class, or "superclass"), without retyping any of them. It's written as class Child(Parent):.
basic_inheritance_demo.py
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)
actual output of basic_inheritance_demo.py
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.

What is... a parent class / subclass? The parent class (also called the superclass or base class) is the class being built on top of. The subclass (also called the child class) is the new class that inherits from it. 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:

subclass_extra_method.py
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())
actual output of subclass_extra_method.py
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.

try_it.py
Click "Run Code" — try adding a Motorcycle(Vehicle) class and creating one.
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.

Quick recap
  • class Child(Parent): makes Child a subclass of Parent.
  • 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.
Sub-topic 2 of 6

2. super().__init__()

At a glance
  • 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.
Why this matters: Sub-topic 1's 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:

What is... 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.
super_init_demo.py
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)
actual output of super_init_demo.py
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:

duplicated_without_super.py
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)
actual output of duplicated_without_super.py — same result, but the risk is hidden
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.

try_it.py
Click "Run Code" — try adding a trunk_capacity parameter the same way num_doors was added.
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.

Quick recap
  • 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 calling super().__init__(...).
Sub-topic 3 of 6

3. Method overriding

At a glance
  • 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.
Why this matters: a generic 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:

What is... overriding? Overriding happens when a subclass defines a method with the same name as one already defined on its parent class. Calling that method on a subclass object runs the subclass's version, not the parent's — the subclass's definition takes priority.
method_overriding_demo.py
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())
actual output of method_overriding_demo.py
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:

super_method_demo.py
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())
actual output of super_method_demo.py
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.

try_it.py
Click "Run Code" — try changing the extra text after the em dash.
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.

Quick recap
  • 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.
Sub-topic 4 of 6

4. Polymorphism

At a glance
  • 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/elif chain checking each object's type is needed at all; overriding already handles it.
Why this matters: Sub-topic 3 showed one 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:

What is... polymorphism? Polymorphism ("many forms") is the ability to call the exact same method name on objects of different classes and have each one respond correctly in its own way, without the calling code needing to know or check which specific class it's dealing with.
polymorphism_demo.py
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())
actual output of polymorphism_demo.py
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.

try_it.py
Click "Run Code" — try adding a Truck subclass and one more object to the list.
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.

Quick recap
  • 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.
Sub-topic 5 of 6

5. isinstance() vs type()

At a glance
  • isinstance(obj, SomeClass) checks whether obj is that class or any subclass of it.
  • type(obj) == SomeClass checks for an exact class match only, ignoring the inheritance relationship entirely.
  • isinstance() is usually the right choice, since a Car genuinely still is a Vehicle.
Why this matters: polymorphism means code often doesn't need to check an object's type at all — but sometimes a real check is genuinely necessary, and the two ways to write that check don't behave the same.

A Car object satisfies both "is it a Car?" and "is it a Vehicle?" — but not "is it a Motorcycle?":

What is... 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.
isinstance_demo.py
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)
actual output of isinstance_demo.py
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.

What is... 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:

isinstance_vs_type_demo.py
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))
actual output of isinstance_vs_type_demo.py
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.

try_it.py
Click "Run Code" — try isinstance(bike, Car) to see it return False.
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)).

Quick recap
  • isinstance(obj, SomeClass) is True for SomeClass and any of its subclasses.
  • type(obj) == SomeClass only 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.
Sub-topic 6 of 6

6. Real-world inheritance & polymorphism in production

At a glance
  • Polymorphism is exactly why long if/elif chains 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.
Pattern to remember: reach for inheritance when the "is-a" test genuinely holds (a 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:

bringing_together_demo.py
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).")
actual output of bringing_together_demo.py
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.

Honest caution: inheritance chains can go too deep. A 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.

Quick recap
  • Polymorphism is why long if/elif type-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.
In the Real World

Points to Remember

← All Chapters Take the Quiz →