Lesson 12 of 15 · Relationships
Composition vs Inheritance
Learn composition in Python: building objects from other objects with has-a relationships and delegation, and a simple rule for choosing composition or inheritance.
- 8 min read
- Intermediate
- Reviewed
- What composition is and what a has-a relationship means
- How to build an object from smaller objects
- What delegation is
- Why inheriting just to reuse code causes problems
- A simple rule for choosing composition or inheritance
Building with parts
A car is not an engine, but a car has an engine. It also has wheels, seats and a radio. Each part is its own thing that can be built, tested and replaced on its own. Software can be built the same way.
Composition in code
class Engine:
def __init__(self, horsepower):
self.horsepower = horsepower
self.running = False
def start(self):
self.running = True
return "Engine started"
class Car:
def __init__(self, brand, horsepower):
self.brand = brand
self.engine = Engine(horsepower) # the car HAS an engine
def start(self):
return f"{self.brand}: " + self.engine.start()
car = Car("Mahindra", 150)
print(car.start())
print(car.engine.running)
print(car.engine.horsepower)Car does not inherit from Engine. Instead, every car creates an Engine object and keeps it in self.engine. You reach the part with a second dot: car.engine.running.
Delegation
In the example, Car.start() does not know how engines start. It delegates to self.engine.start(). The car is in charge of car things, the engine of engine things. Each class stays small and focused.
Objects that hold many objects
Composition is often a list of other objects:
class Song:
def __init__(self, title, seconds):
self.title = title
self.seconds = seconds
class Album:
def __init__(self, name):
self.name = name
self.songs = [] # an album HAS songs
def add(self, song):
self.songs.append(song)
def longest(self):
best = self.songs[0]
for song in self.songs:
if song.seconds > best.seconds:
best = song
return best.title
album = Album("Focus")
album.add(Song("Morning", 210))
album.add(Song("Deep work", 340))
album.add(Song("Evening", 185))
print(len(album.songs), "songs")
print("Longest:", album.longest())The trap: inheriting just to reuse code
Suppose you want a stack: a pile where you can only add to the top and take from the top, like a pile of plates. A list already has append() and pop(), so it is tempting to inherit from list:
class Stack(list):
def push(self, item):
self.append(item)
plates = Stack()
plates.push("blue plate")
plates.push("red plate")
plates.insert(0, "sneaky plate") # this should not be allowed!
plates.sort() # neither should this
print(plates)Because Stack is a list, it inherited every list method, including ones that break the rules of a stack. Anyone using it can put plates in the middle.
With composition, the stack has a list inside it, and only offers the methods that make sense:
class Stack:
def __init__(self):
self._items = [] # a stack HAS a list
def push(self, item):
self._items.append(item)
def pop(self):
return self._items.pop()
def peek(self):
return self._items[-1]
def __len__(self):
return len(self._items)
plates = Stack()
plates.push("blue plate")
plates.push("red plate")
print(plates.pop())
print(plates.peek(), len(plates))
print(hasattr(plates, "insert"))Now insert does not exist on a stack at all. The list is a hidden detail that could even be swapped for something else later, without breaking any code that uses the stack.
How to choose
| Ask yourself | If yes, use |
|---|---|
| Is the new thing a kind of the existing thing? ("A dog is an animal.") | Inheritance |
| Does the new thing contain or use the existing thing? ("A car has an engine.") | Composition |
| Should it have all of the other class's methods? | Inheritance |
| Do you only need some of its abilities? | Composition |
Experienced programmers often say: prefer composition over inheritance. Inheritance links classes tightly, so a change in the parent can break every child. Composition keeps the parts loosely connected, so each one can be changed or swapped on its own. Use inheritance when the is-a sentence is clearly true, and composition the rest of the time.
Swapping parts
A big advantage of composition: you can give an object a different part without changing its class. This is polymorphism and composition working together.
class EmailSender:
def send(self, text):
return f"Email: {text}"
class SmsSender:
def send(self, text):
return f"SMS: {text}"
class Reminder:
def __init__(self, sender):
self.sender = sender # any object with a send() method
def remind(self, task):
return self.sender.send(f"Do not forget: {task}")
print(Reminder(EmailSender()).remind("submit the report"))
print(Reminder(SmsSender()).remind("call the client"))Reminder works with any sender. To add WhatsApp messages later, you write a new sender class. Reminder never changes.
Common mistakes
Use composition to build a playlist that is made up of song objects.
# Write two classes:
# - Song(title, seconds)
# - Playlist(name) that HAS a list of songs, with:
# add(self, song) adds a Song
# total_seconds(self) returns the total length in seconds
# describe(self) returns e.g. "Study mix: 3 songs, 10 min 30 s"
# Tip: minutes = total // 60 and seconds = total % 60
mix = Playlist("Study mix")
mix.add(Song("Lo-fi beats", 200))
mix.add(Song("Rain sounds", 250))
mix.add(Song("Piano focus", 180))
print(mix.total_seconds())
print(mix.describe())
# Output must be exactly:
# 630
# Study mix: 3 songs, 10 min 30 s
A Library contains many Book objects. Which design fits best?
Summary
- Composition builds an object out of other objects stored as attributes.
- It models a has-a relationship. Inheritance models an is-a relationship.
- Delegation means handing a job to one of your parts.
- Inheriting just to reuse code also brings unwanted methods. Composition exposes only what you choose.
- Prefer composition, and use inheritance when "X is a kind of Y" is clearly true.
You have finished the Relationships module. Next: protecting an object's data with encapsulation.
Finished reading? Tick it off to track your progress.