Content · Programming · Python

Python Composition vs Inheritance: Choosing a Design

Decide when composition is clearer than inheritance for code reuse.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Decide when composition is clearer than inheritance for code reuse.

How It Works


Composition models has-a relationships by storing one object inside another. Inheritance models is-a relationships with substitutability. Favor composition when behaviors change independently or need swapping.

Composition supports small test doubles and dependency injection.

Step-by-Step Example


class EmailSender:
    def send(self, message):
        return f"Email: {message}"

class AlertService:
    def __init__(self, sender):
        self.sender = sender

    def alert(self, message):
        return self.sender.send(message)

print(AlertService(EmailSender()).alert("Ready"))

Understanding the Example


  • The class groups related state and methods so each instance can manage its own values.
  • The function definition gives the operation a reusable name and makes its inputs explicit.

A successful run of this example prints the following output:

Email: Ready

Where This Fits in a Real Program


A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.

Practice: Try It Yourself


Replace EmailSender with a console sender without changing AlertService.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Using subclassing merely to access one helper method from another class.
  • Hardcoding a dependency when injecting an object would simplify testing and reuse.

Key Takeaways


  • Decide when composition is clearer than inheritance for code reuse.
  • Composition models has-a relationships by storing one object inside another.
  • Composition supports small test doubles and dependency injection.
Share this resourceSend this page to someone who may find it useful.