the full guide

Inner classes and composition

An inner class is a class defined inside another, usually to keep a closely related helper together. Composition means building an object from other objects (a car has an engine), as opposed to inheritance (a car is a vehicle).

6 min Intermediate

What you need: The earlier topics of this module.

Definition

An inner class is a class defined inside another, usually to keep a closely related helper together. Composition means building an object from other objects (a car has an engine), as opposed to inheritance (a car is a vehicle).

In simple words

Ask: is it an "is a" or a "has a"? A dog is an animal, so that's inheritance. A dog has a collar, so that's composition. Most of the time, "has a" is the better design.

Why it matters

Composition lets you swap parts easily. PyTorch models are built this way: a network has layers as attributes.

How it works

In code

composition.py
class Engine:
    def start(self):
        return "engine on"

class ElectricEngine(Engine):
    def start(self):
        return "silent motor on"

class Car:
    def __init__(self, engine):
        self.engine = engine          # has an engine

    class Key:                        # inner class: only makes sense with Car
        def __init__(self, code):
            self.code = code

    def drive(self):
        return f"{self.engine.start()}, driving"

print(Car(Engine()).drive())
print(Car(ElectricEngine()).drive())   # swap the part, no new Car class
print(Car.Key("A1").code)

Output

engine on, driving
silent motor on, driving
A1

Common mistakes

  • Inheriting just to reuse a method when the "is a" relationship isn't true.
  • Using inner classes when a normal class would be clearer.

Check yourself

Question 1

1. A library has books. Which should you use?

Question 2

2. A Dog class extending an Animal class is:

Summary

  • "Is a" suggests inheritance, and "has a" suggests composition.
  • Composition makes parts swappable.

Finished reading?

Sources: The Python Tutorial, python.org