Python Classes and Objects · Lesson 89 of 149

Python Composition or Inheritance?

What you will learn

  • The difference between "is-a" and "has-a"
  • Composition: an object that holds other objects
  • Delegation: passing work to the held object
  • Why composition can be safer than inheritance
  • Dependency injection and swappable strategies
  • Guidelines for choosing between the two

1. Two ways to relate classes

When one class needs the abilities of another, there are two main designs:

Relationship Meaning Tool Example
is-a the new class is a special kind of the old one inheritance: class Dog(Animal) (lesson 13.5) a Dog is an Animal
has-a the new class uses the old one as a part composition: an attribute holding an object a Car has an Engine

The test is a simple sentence: say "A is a B" or "A has a B" aloud. Whichever sounds right is the one to use. "A Car is an Engine" is plainly wrong, so a Car should not inherit from Engine:

class Engine:
    def __init__(self, hp):
        self.hp = hp
        self.running = False

    def start(self):
        self.running = True
        return "engine started"

class Car:
    def __init__(self, brand, hp):
        self.brand = brand
        self.engine = Engine(hp)

    def start(self):
        return f"{self.brand}: {self.engine.start()}"

    def power(self):
        return self.engine.hp

c = Car("Fiat", 90)
print(c.start())
print(c.power(), c.engine.running)
print(isinstance(c, Engine))
Fiat: engine started
90 True
False

The Car owns an Engine in its attribute engine, and forwards the work to it: start calls self.engine.start(). This is composition: the car is composed of parts. Object-oriented programmers sum it up: "prefer composition over inheritance."

Quick check: which sounds right, "a Library is a Book" or "a Library has Books"?

"A Library has Books", so a Library object should hold a list of Book objects (composition).

2. Delegation

Passing a request to an inner object is called delegation. The outer object keeps a small, clear interface, and does the real work through its parts. A few examples from earlier lessons:

  • the Cart held a list of Item objects and asked each for its total() (lesson 13.2);
  • Person held an Address and used its text:
class Address:
    def __init__(self, city, zip_):
        self.city = city
        self.zip = zip_

    def __str__(self):
        return f"{self.city} {self.zip}"

class Person:
    def __init__(self, name, address):
        self.name = name
        self.address = address

    def label(self):
        return f"{self.name}, {self.address}"

print(Person("Rina", Address("Dhaka", "1207")).label())
Rina, Dhaka 1207

An object may hold several parts (self.wheels = [Wheel(), Wheel()]), or parts of different kinds. Complex programs are built by putting simple objects together.

3. Why composition can be safer: the Stack

Suppose you need a stack: last in, first out, with push, pop and peek (lesson 7.6). A tempting shortcut is to inherit from list:

class Stack(list):
    def push(self, x):
        self.append(x)

s = Stack()
s.push(1)
s.push(2)
print(s)
s.insert(0, 9)
print(s)
print(hasattr(s, "insert"))
[1, 2]
[9, 1, 2]
True

It works, but a "stack" now also has insert, sort, reverse and everything else a list has. Anybody can break the stack rule with s.insert(0, 9). The subclass is not really a list in spirit (a stack should not allow insertion in the middle), so the "is-a" sentence is wrong.

With composition, the list is hidden inside, and only the operations you choose are exposed:

class Stack2:
    def __init__(self):
        self._items = []

    def push(self, x):
        self._items.append(x)

    def pop(self):
        return self._items.pop()

    def peek(self):
        return self._items[-1]

    def __len__(self):
        return len(self._items)

    def __repr__(self):
        return f"Stack2({self._items})"

s2 = Stack2()
s2.push(1)
s2.push(2)
print(s2)
print(s2.pop(), s2.peek(), len(s2))
print(hasattr(s2, "insert"))
Stack2([1, 2])
2 1 1
False

Stack2 has exactly the interface of a stack, nothing more. Later, you could change the inside from a list to a deque or a linked list, and no code that uses the stack needs to change.

Forwarding everything: a wrapper

If you really want to expose every method of the inner object, a wrapper can forward unknown attributes with __getattr__ (lesson 13.7):

class Wrapper:
    def __init__(self, inner):
        self._inner = inner

    def __getattr__(self, name):
        return getattr(self._inner, name)

w = Wrapper([3, 1, 2])
print(w.count(1), w.index(2))

w2 = Wrapper(Engine(50))
print(w2.hp, w2.start())
1 2
50 engine started

The wrapper does not inherit anything, yet w.count(...) works, because the missing attribute is looked up on the inner object. Use this to add behaviour around an existing object (logging, caching, access control) without changing its class.

4. Handing in the parts: dependency injection

A class that creates its own parts is tied to them. A class that receives them from outside is flexible. Handing a part in is called dependency injection:

class Logger:
    def __init__(self):
        self.lines = []

    def log(self, m):
        self.lines.append(m)

class Service:
    def __init__(self, logger):
        self.logger = logger

    def run(self, x):
        self.logger.log(f"running {x}")
        return x * 2

lg = Logger()
svc = Service(lg)
print(svc.run(5), lg.lines)
10 ['running 5']

Service does not care what kind of logger it gets, only that it has a log(message) method (duck typing, lesson 13.6). So you can give it a different logger:

class PrintLogger:
    def log(self, m):
        print("LOG:", m)

Service(PrintLogger()).run(7)
LOG: running 7

And, very usefully, a fake for tests, which only counts calls:

class FakeLogger:
    def __init__(self):
        self.calls = 0

    def log(self, m):
        self.calls += 1

fk = FakeLogger()
Service(fk).run(1)
Service(fk).run(2)
print(fk.calls)
2

A test can check that the service logged, with no real file or network involved. This is one of the biggest practical benefits of composition (lesson 18.4).

5. Swappable behaviour: strategies

When part of an object's behaviour may vary (a discount, a sorting rule, a way of moving), put that behaviour in its own object, and hold it as a part. The held object is called a strategy. It can even be swapped at run time:

class Discount:
    def apply(self, total):
        return total

class TenPercent(Discount):
    def apply(self, total):
        return total * 0.9

class Flat(Discount):
    def __init__(self, n):
        self.n = n

    def apply(self, total):
        return max(0, total - self.n)

class Order:
    def __init__(self, prices, discount=None):
        self.prices = prices
        self.discount = discount or Discount()

    def total(self):
        return round(self.discount.apply(sum(self.prices)), 2)

print(Order([10, 20]).total())
print(Order([10, 20], TenPercent()).total())
print(Order([10, 20], Flat(5)).total())
print(Order([3], Flat(5)).total())

o = Order([100])
o.discount = TenPercent()
print(o.total())
30
27.0
25
0
90.0

Order knows nothing about how a discount works; it just calls apply. To add a new kind of discount, write one new class; Order is not touched. (The discount classes here use inheritance among themselves, a good "is-a" case: a TenPercent is a Discount.)

A simpler form of a strategy in Python is just a function (lesson 11.7): Order(prices, discount=lambda t: t * 0.9). Use a class when the strategy has its own data (like Flat(n)) or several methods.

6. Choosing

Choose inheritance when Choose composition when
the sentence "B is an A" is true the sentence "B has an A" is true
subclasses share an interface and a contract (anything that works with A works with B) you only want to reuse some code or a feature
you want polymorphism over a family of classes you want to swap parts at run time or in tests
the hierarchy is shallow (one or two levels) the combination of features would make a deep or tangled hierarchy
the parent was designed to be extended the other class is a built-in or library class that you do not control

A few more guidelines:

  • Prefer composition by default; it keeps classes small and independent.
  • Keep inheritance for true "is-a" families (shapes, employees, exceptions).
  • Do not inherit just to reuse a few methods: hold the object and call it.
  • Combine them freely: a Car has an Engine (composition), and a Truck is a Car (inheritance).
  • Mixins (lesson 13.13) are a middle road for adding small abilities to many classes.

Worked example: a notification system

A Notifier sends a message through any channel (email, text, console), and records what it sent in a history. The channels are separate objects handed in, so a new channel is just a new class, and tests can use a fake.

class ConsoleChannel:
    def send(self, to, text):
        return f"console -> {to}: {text}"


class SmsChannel:
    def __init__(self, max_len=20):
        self.max_len = max_len

    def send(self, to, text):
        return f"sms -> {to}: {text[:self.max_len]}"


class FakeChannel:
    def __init__(self):
        self.sent = []

    def send(self, to, text):
        self.sent.append((to, text))
        return "ok"


class Notifier:
    def __init__(self, channel):
        self.channel = channel
        self.history = []

    def notify(self, to, text):
        result = self.channel.send(to, text)
        self.history.append(result)
        return result

    def switch(self, channel):
        self.channel = channel
        return self


n = Notifier(ConsoleChannel())
print(n.notify("Rina", "Your order has shipped"))

n.switch(SmsChannel(10))
print(n.notify("Sam", "Your order has shipped"))
print(len(n.history))

fake = FakeChannel()
Notifier(fake).notify("Lee", "Test")
print(fake.sent)
console -> Rina: Your order has shipped
sms -> Sam: Your order
2
[('Lee', 'Test')]
Idea In the example
composition a Notifier has a channel and a history
delegation notify passes the work to self.channel.send(...)
dependency injection the channel is given to Notifier
strategy swapped at run time switch(SmsChannel(10)) changes how messages go
easy testing FakeChannel records calls and sends nothing real

The channel classes share no parent: they only share the send(to, text) method (duck typing). The names and messages are made up.

Common mistakes

  • Inheriting from a class "to get its methods" when the relationship is not "is-a".
  • Subclassing a built-in type (list, dict) and exposing methods that break your rules.
  • Creating the parts inside the class (self.logger = Logger()) when they should be handed in, which makes testing hard.
  • Deep inheritance trees for combinations of features.
  • Forgetting to delegate (self.engine.start()) and duplicating the code.
  • Giving the outer class every method of the inner one when a small interface would do.

Key takeaways

  • Is-a suggests inheritance; has-a suggests composition (an object stored in an attribute, with work delegated to it).
  • Composition keeps the interface small (a Stack that wraps a list exposes only push, pop, peek) and lets you change the inside later.
  • Dependency injection (passing parts in) makes code flexible and testable; a fake part replaces a real one in tests.
  • A strategy object (or a function) makes behaviour swappable, even at run time.
  • Prefer composition by default; use inheritance for true "is-a" families with a shared contract.

Practice

1. Should a Library class inherit from list to hold its books? Why or why not?

Show answer

No: "a Library is a list" is not true. A Library has books, so it should hold a list in an attribute and offer its own methods such as add_book and find.

2. What does delegation mean?

Show answer

An object passes a request on to another object it holds, such as Car.start calling self.engine.start().

3. Why is it better to give Service a logger as an argument than to create it inside?

Show answer

You can pass a different logger (or a fake for testing) without changing Service. Creating it inside ties the class to one logger.

4. Name one risk of class Stack(list).

Show answer

It exposes all list methods (insert, sort, ...), so outside code can break the stack rules. The interface is bigger than a stack should have.

5. Give an example of a strategy that is just a function.

Show answer

sorted(words, key=len): len is a strategy for how to order the items. Likewise a discount lambda total: total * 0.9.

6. When is inheritance still the right choice?

Show answer

When the subclass is truly a special kind of the parent, shares its interface and contract, and you want polymorphism over the family (for example shapes, employees, exceptions).