OOP in Python, part 17: Composition
MP 63: An important complement to inheritance.
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; it will wrap up over the next few posts.
Inheritance is a natural concept to introduce when teaching and discussing OOP. As powerful as it is, however, it can lead to problematic models of real-world objects and abstract concepts. Many of these issues can be addressed using a concept called composition.
With inheritance, you model complex systems by writing classes that extend the behavior of other classes. Inheritance is a powerful concept, but it can create problems when the classes become too tightly coupled. For example, making changes to an existing class can affect all subclasses, even the ones you have no control over.
When using composition, you write smaller classes representing individual parts of a system. The resulting connections between classes are much less likely to create issues as each part of the system evolves.
If you’ve written code that uses OOP there’s a fair chance you’ve used composition before, even if you haven’t heard the term specifically. As an example, consider the context of modeling a library that lends books to its patrons.
Here’s the first part of library.py:
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.