Syncing account progress…

Back

Advanced · 13 min

Composition

Build larger objects from smaller objects with clear responsibilities.

Combine objects

Composition stores one object inside another. Each class can stay focused on one responsibility.

class Engine:
    def start(self):
        return "ready"

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

print(Car().engine.start())

Output

ready

Delegate work

A containing object can expose a simple method that delegates a task to one of its parts.

class Formatter:
    def label(self, name):
        return name.upper()

class Report:
    def __init__(self):
        self.formatter = Formatter()
    def title(self, name):
        return self.formatter.label(name)

print(Report().title("sales"))

Output

SALES

Composition

  1. Read both composition examples before answering.
  2. Run the task, compare its exact output, and revise the code if needed.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Compose a notification

Complete Notification.send so it uses its formatter to return Hello, Ada. Display the result.

Practice