Choose Composition or Inheritance
Core idea
Use inheritance when a specialized object can honor the contract of a base type. Use composition when an object needs another object to do part of its work. A composed object holds a collaborator and delegates calls to it. Composition can make behavior replaceable without adding subclasses; inheritance is useful when a stable shared interface and specialization genuinely fit.
class Ticket: def price(self): return 10class ChildTicket(Ticket): def price(self): return 5for ticket in [Ticket(), ChildTicket()]: print(ticket.price())Both types satisfy the price operation used by the caller.
Delegate to a component
class FlatFee: def cost(self, weight): return 4class Shipment: def __init__(self, fee): self.fee = fee def total(self, weight): return self.fee.cost(weight)print(Shipment(FlatFee()).total(3))A shipment has a fee policy; it is not itself a fee policy.
Replace the collaborator
class FlatFee: def cost(self, weight): return 4class WeightFee: def cost(self, weight): return weight * 2class Shipment: def __init__(self, fee): self.fee = fee def total(self, weight): return self.fee.cost(weight)for policy in [FlatFee(), WeightFee()]: print(Shipment(policy).total(3))The shipment uses either policy through the same operation without inheriting from it.
Common mistake
Do not inherit merely to access a helper method. Consider whether callers expecting the base type can safely use the derived object. If not, a collaborator is often clearer.
Practice
Add a minimum-charge policy with cost(weight), then use it in Shipment without changing Shipment. Explain why Shipment need not subclass the policy.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Select composition or inheritance
Check your understanding of composition versus inheritance.
What is printed?
class Fee: def cost(self, n): return n * 2class Order: def __init__(self, fee): self.fee = fee def total(self, n): return self.fee.cost(n)print(Order(Fee()).total(3))What is printed?
class Fee: passclass Order: def __init__(self, fee): self.fee = feeprint(isinstance(Order(Fee()), Fee))What is printed?
class A: def cost(self): return 3class B: def cost(self): return 8class Order: def __init__(self, fee): self.fee = fee def total(self): return self.fee.cost()print(Order(A()).total(), Order(B()).total())A shipment needs a replaceable pricing policy. Which design is usually most direct?