OOP in Python, part 18: Composition and inheritance
MP 64: A mix of the two approaches is often the most practical solution.
Note: This post is part of a series about OOP in Python. The posts in this series (except for the first one) will only be available to paid subscribers for the first 6 weeks. After that they will be available to everyone. Thank you to everyone who supports my ongoing work on Mostly Python.
This has been a long series; part 20 will be the last post in the series.
In the last post we discussed how composition can be used to model has a relationships, such as a library that has a collection of books. But what happens when there are more relationships in the overall scenario you’re trying to model? What if you have a mix of has a and is a relationships?
In real-world situations you often need to use a mix of inheritance and composition. In this post we’ll extend the library example to include a mix of inheritance where appropriate, and composition where appropriate.
Books and magazines
A library that only lends books is a little limiting. Let’s expand the library to include a collection of magazines as well.
To do this, we need to think about two kinds of relationships:
What’s the relationship between a library and a magazine?
What’s the relationship between a magazine and a book?
If the word relationship isn’t helping you think clearly about this, try using the word connection instead.
Libraries and magazines
The relationship (or connection) between a library and a magazine is easier to think about, so let’s start there. A library has a magazine, or a collection of magazines. That steers us toward composition—the
Library class will have a collection of
Books and magazines: conceptual thinking
The relationship between books and magazines is less clear. A book doesn’t have a magazine, and a magazine doesn’t have a book. So we’re probably not going to be using composition between them.1
Let’s consider the is a relationship. A book is not a magazine, and a magazine is not a book. They seem related somehow though, especially in the context of a library. We’ll do some common things with them. We’ll catalog them, we’ll loan them out, and people will return them. So they’ll have some common attributes and behaviors, which leads us towards inheritance. Is there any way we can fill in the following blanks with the same word?
A book is a _____.
A magazine is a _____.
Keep reading with a 7-day free trial
Subscribe to Mostly Python to keep reading this post and get 7 days of free access to the full post archives.