Object-oriented programming · lesson 15 of 17
Parts in this lesson
Aclass DVD(LibraryItem)4.5: is a
Bself.policy = policyhas a
Cself.policy.fine_for(days)delegation: pass the work on
Da if test else bone of two values

Composition over inheritance

Last updated

Inheritance says one class is a kind of another. Composition says one object has another. Both reuse code, and choosing wrongly makes a program hard to change. In this lesson you'll tell the two apart, watch a family of member classes multiply out of control, replace it with members that hold a borrowing policy, pass work on to the object you hold, and learn when inheritance is still the right tool.

By the end of this lesson you can

  • Tell an "is a" relationship from a "has a" one, and pick inheritance or composition to match
  • Explain why a class hierarchy built from combinations grows out of control
  • Give an object a part it holds, and delegate work to it
  • Say when inheritance is still the better choice

"Is a" or "has a"

There are two ways to build a class out of another.

  • Inheritance: a DVD is a library item. class DVD(LibraryItem) means every DVD is also a LibraryItem, with everything a library item has.
  • Composition: a loan has an item. The loan holds the item in an attribute, as in lesson 3.3. A loan isn't a kind of item.
Step 1 code main.py
Edit the code, then run it again

Line 18 is True: a DVD counts as a library item. Line 19 is False: a loan only holds one. Saying the sentence out loud is a good test. "A DVD is a library item" sounds right. "A loan is a library item" doesn't.

Is a, or has a?
SentenceDesign
A DVD and a library itemA DVD is a library itemInheritance: class DVD(LibraryItem)
A loan and an itemA loan has an itemComposition: self.item = item
A member and their loansA member has loansComposition: self.loans = []
A member and a borrowing policyA member has a policyComposition: self.policy = policy

The last row is the subject of this lesson.

When a hierarchy goes wrong

The library has three kinds of member. Students can borrow 6 items, staff pay no fines, and everyone else gets the standard deal. Inheritance looks like a fit: a student member is a member.

One small new piece: "pays fines" if self.fines else "no fines" on line 9 picks one of two values. It's an if and else squeezed into one line, for when each side is a single value.

One class for every mix of kinds: the class explosion
100%
Member
  • +limit: int
  • +fines: bool
  • +name: str
  • +__init__(name: str)
  • +describe(): str
StudentMember
  • +limit: int
StaffMember
  • +fines: bool
StudentStaffMember
  • Class Member; attributes: limit, fines, name; methods: __init__, describe.
  • Class StudentMember; inherits from Member; attributes: limit; no methods of its own.
  • Class StaffMember; inherits from Member; attributes: fines; no methods of its own.
  • Class StudentStaffMember; inherits from StudentMember and StaffMember; no attributes of its own; no methods of its own.
Step 2 code main.py
Edit the code, then run it again

It works. Then Kim turns up, who is both a student and on the staff. That needs a fourth class, StudentStaffMember, with two parents (lesson 4.7). Now imagine the library adds guest members, who can borrow only 1 item. To cover every mix you'd need GuestMember, GuestStudentMember, GuestStaffMember, GuestStudentStaffMember… Each new kind of member doubles the number of classes.

Try it: add a GuestMember with limit = 1, then the classes for a guest who is also a student or on the staff. Count how many classes you need, and notice they hold almost no code. The classes multiply, but the rules don't.

There's a second problem. If Ana leaves her course and joins the staff, her object is a StudentMember for life. An object can't change its class.

A member has a borrowing policy

The rules, a limit and whether fines apply, aren't what a member is. They're something a member has: a borrowing policy. So make Policy its own small class, here a dataclass from lesson 3.6, and give each member one.

Step 3 code main.py
Edit the code, then run it again
  • There's one Member class, and three ready-made policies on lines 11 to 13.
  • Kim's mix of student and staff rules on line 26 is just another Policy. No new class is needed.
  • Ana changes policy on line 30 by changing one attribute, while the program runs.

A guest is now one more line, GUEST = Policy("guest", 1, True), not four more classes.

Delegating to an object you hold

When other code asks a member for a fine, the member doesn't work it out. It passes the job to its policy: self.policy.fine_for(days_late) on line 23. Passing work on to an object you hold is called delegation.

The policy here is a plain class with a method, so different policies can have different fine rules: 25 cents a day up to 500, as in lesson 1.P, or nothing for staff.

A Member has a Policy: composition
100%
Member
  • +name: str
  • +policy: Policy
  • +loans: list[str]
  • +__init__(name: str, policy: Policy)
  • +can_borrow(): bool
  • +fine_for(days_late: int): int
Policy
  • +limit: int
  • +fine_per_day: int
  • +max_fine: int
  • +__init__(limit: int, fine_per_day: int, max_fine: int)
  • +fine_for(days_late: int): int
  • Class Policy; attributes: limit, fine_per_day, max_fine; methods: __init__, fine_for.
  • Class Member; attributes: name, policy, loans; methods: __init__, can_borrow, fine_for.
  • Member holds one Policy in policy.
Step 4 code main.py
Edit the code, then run it again

Code that uses a Member calls sam.fine_for(4) and never needs to know a policy exists. That keeps the design free to change later, which is encapsulation again (lesson 4.2). Line 31 fills Sam's loans from outside only to keep the example short.

When inheritance is still right

None of this makes inheritance bad. It's the right tool when the "is a" sentence is true, stays true, and the child can stand in for the parent anywhere. Python's own exceptions are a family like that, as lesson 4.8 showed.

Inheritance or composition
If…Use
The child really is a kind of the parent, everywhere and alwaysInheritance
The child works wherever the parent does (lesson 4.9)Inheritance
The tree stays shallow, one or two levelsInheritance
A family of errors, like LibraryError (lesson 4.8)Inheritance
The object has the thing, or uses itComposition
Kinds combine, like student and staffComposition
The part may change while the program runsComposition
You want only some of another class’s methodsComposition

A good habit: reach for composition first, and use inheritance when the "is a" test clearly passes. The capstone does both: books, DVDs and magazines inherit from LibraryItem, and members hold a policy.

In other languages

This step is optional. It's for anyone who will meet Java or Rust later.

Reusing code in three languages
PythonJavaRust
Reusing code by “is a”Inheritance, even from several parentsextends, one parentNo inheritance
Reusing code by “has a”An attribute holding the partA field holding the partA field holding the part
Passing work onCall the part’s method yourselfThe sameThe same
Advice“Composition over inheritance” is common adviceThe same advice is classic in JavaThe language makes the choice for you

Rust has no inheritance at all, so composition and traits do all the work: see Simple Rust 4.1.

Check what you learned

Three questions. Pick an answer, then check it.

Which is a "has a" relationship?
A member can switch from a student policy to a staff policy halfway through the year. Which design handles that by changing one attribute?
What is delegation?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python