Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Advanced Python & Software Engineering — Alpha School

Lesson 2: Inheritance, Composition and Polymorphism

Once you have written a few classes, you will notice that some of them share most of their behaviour. A Student and a Teacher are both people with names and email addresses; a Dog and a Cat both have a name and a way of making a sound. Writing the shared parts twice is wasteful, and worse, it means fixing a bug twice. Inheritance solves this: a class can inherit from another class, receiving all of its attributes and methods, and then add or change only what is different.

The class you inherit from is called the parent (or base) class, and the new class is the child (or subclass). The child can override a parent method by defining a method with the same name, and it can call the parent's version with super(). In the example below, Animal defines speak as a generic placeholder, while Dog and Cat each override it with their own sound. Code that works with animals does not need to know which kind it has — it just calls speak() and the right version runs. That idea, one interface with many forms, is called polymorphism.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return "(silence)"


class Dog(Animal):
    def speak(self):
        return "Woof!"


class Cat(Animal):
    def speak(self):
        return "Meow!"


for pet in [Dog("Rex"), Cat("Mimi"), Animal("Mystery")]:
    print(pet.name, "says", pet.speak())

Inheritance or composition?

Inheritance is powerful, but it is not always the right tool. A useful rule of thumb is the is-a test: a dog is an animal, so inheritance fits. But a car has an engine — it is not an engine — so the car should hold an Engine object as an attribute instead of inheriting from it. That pattern is called composition, and experienced Python programmers reach for it more often than beginners expect. Composition keeps classes small and flexible: you can swap one engine for another without rewriting the car, and you can reuse the engine class in a boat or a generator.

Inheritance also has a cost that is easy to miss. When a child class depends on the internals of its parent, a change to the parent can silently break the child — the two classes become tightly coupled. Deep inheritance chains, where a class inherits from a class that inherits from a class, are a classic source of confusion. A practical guideline is to prefer composition when you can, use inheritance for a genuine is-a relationship, and keep hierarchies shallow — usually no more than two or three levels. Python also supports multiple inheritance, but that is a topic for later, and a good reason to keep your designs simple from the start.

Going further

When Python looks up a method, it searches the class of the instance first, then its parent, then the grandparent, and so on — an order called the method resolution order (MRO). You can see it with Dog.__mro__, which lists the classes in the order Python searches them. For a simple chain the order is exactly what you would expect, and you rarely need to think about it. It only becomes interesting with multiple inheritance, where two parents define the same method — one more reason to keep hierarchies shallow and simple.

Python also supports a looser style than inheritance: duck typing. The name comes from the saying that if something walks like a duck and quacks like a duck, it is a duck. Code that calls pet.speak() does not check what class the pet is — it only needs the object to have a speak method. That is why the loop in this lesson works for any animal, including ones defined in code you have never seen. Polymorphism in Python often works this way: through shared behaviour, not shared ancestry.

A useful exercise is to build a small hierarchy of your own and test the is-a rule on it. Start with a Vehicle class that has a speed and a move() method, then add Car and Bicycle subclasses that override move() in their own way. Then add a class that does not fit the hierarchy — a Garage, which holds vehicles but is not one — and implement it with composition instead, storing a list of vehicles as an attribute. Writing both patterns side by side, in the same small program, is the fastest way to feel the difference between inheriting behaviour and holding an object that provides it.

Key Terms

Inheritance
A class receiving the attributes and methods of a parent class, then adding or changing behaviour.
Parent class (base class)
The class being inherited from; also called the superclass.
Child class (subclass)
The class that inherits; also called the derived class.
Override
Defining a method in a child class with the same name as a parent method, replacing its behaviour.
super()
A built-in that gives access to the parent class, used to call a parent method from a child.
Polymorphism
Different classes responding to the same method call in their own way, so shared code can treat them alike.
Composition
Building a class by holding objects of other classes as attributes (a has-a relationship) instead of inheriting.

Discussion Questions

  1. A square is a rectangle in geometry. Would you make Square inherit from Rectangle in code? What could go wrong with the width and height?
  2. When would you choose composition over inheritance for a new feature? Give an example from a program you might write.
  3. Why does polymorphism make code easier to extend — for example, adding a Bird class to the animal example without changing the loop?

Practice Questions

  1. In the example, what does Animal("Mystery").speak() return, and why?
  2. Write a Bird subclass of Animal whose speak returns "Chirp!" and test it in the loop.
  3. A Library holds many Book objects. Is that inheritance or composition?
  4. What does super().__init__(name) do inside a child class?
  5. Give one risk of a deep inheritance chain.
Show answers
  1. "(silence)". Animal defines speak itself, and no subclass overrides it for that instance.
  2. class Bird(Animal): def speak(self): return "Chirp!" The loop needs no changes: polymorphism means the new class works with the existing code.
  3. Composition. A library has books — a has-a relationship — so it should store Book objects as attributes, not inherit from Book.
  4. It calls the parent class's __init__ with the given arguments. This lets the child reuse the parent's setup instead of duplicating it.
  5. A change to a parent can silently break distant children. The classes become tightly coupled, and behaviour is hard to trace through many levels.
Keep reading to complete this lesson