Glossary

Composition

Composition is an object-oriented design pattern in which a class achieves functionality by containing instances of other classes as attributes, rather than inheriting from them. The phrase "composition over inheritance" is one of the most quoted principles in software design, originating from the Gang of Four's Design Patterns book.

In Python, composition is natural and lightweight. If a Car needs an engine, it holds an Engine instance as an attribute (self.engine = Engine()) rather than inheriting from Engine. This avoids the tight coupling that inheritance creates: you can swap in a different engine implementation without changing the Car class hierarchy. Composition also avoids the complexities of multiple inheritance and the diamond problem.

The relationship expressed by composition is "has-a" rather than "is-a." A car has an engine; a dog is an animal. Composition works especially well with Python's duck typing: the Car doesn't need the Engine to inherit from any particular base class — it just needs it to have the right methods. Dependency injection, strategy pattern, and delegation are all forms of composition that Python makes straightforward.

Related terms: Inheritance, Duck Typing, Class

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.