composition

In object-oriented programming (OOP), composition is a fundamental concept that allows you to build composite objects by combining simpler ones.

Rather than using inheritance to create a new class, you can use composition to include objects of other classes as attributes. This approach provides more flexibility and modularity because it allows you to change the behavior of a class by replacing one of its components.

You should favor composition over inheritance when you want to use functionality from multiple classes without creating a rigid class hierarchy. It promotes code reuse and leads to more maintainable and adaptable codebases.

Example

Here’s a quick example of composition in Python:

Python vehicles.py
class Engine:
    def start(self):
        print("Engine started!")

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

    def start(self):
        self.engine.start()

# Usage
car = Car()
print(car.start())  # Usage: Engine started!

In this example, the Car class has Engine as a component. Instead of inheriting from Engine, Car uses an instance of Engine to perform actions, demonstrating composition.

Tutorial

Inheritance and Composition: A Python OOP Guide

In this step-by-step tutorial, you'll learn about inheritance and composition in Python. You'll improve your object-oriented programming (OOP) skills by understanding how to use inheritance and composition and how to leverage them in their design.

intermediate best-practices python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 10, 2025 • Reviewed by Leodanis Pozo Ramos