Browse OOP reference
Relationships and dispatch

What is composition?

On this page

Composition builds behaviour from components. A PriceCalculator can hold a TaxPolicy and use it to compute one part of a quote. Replacing the policy changes that decision independently. UML composite aggregation adds a stricter ownership meaning, so a field alone does not establish a filled-diamond relationship.

Relationship diagram

Quotetotal(cents)Exempttax(cents)uses policy

Worked example

Python
class Exempt:
    def tax(self, cents):
        return 0

class Quote:
    def __init__(self, policy):
        self.policy = policy
    def total(self, cents):
        return cents + self.policy.tax(cents)

assert Quote(Exempt()).total(750) == 750

Python tutorial on classes

Explore class relationships in the OOP Playground

What is aggregation?What is information hiding?What are metaclasses?

All OOP questions

Search ObjectFAQ