B3.2.4 Composition and aggregation
HL onlyCommand term: Explain1. Who survives? The lifecycle stepper
A Library creates its own shelves (composition) but is given its members (aggregation). Step through, then delete the library and see which parts disappear with it.
2. Draw the right line: UML relationships
Choose the relationship for each pair and watch the UML diagram change. A hollow diamond means aggregation, a filled diamond means composition, and the diamond sits next to the whole.
3. Build a car from parts: composition versus inheritance
Choose the parts. With composition, one Car class is built from component objects and can even swap a part while running. With inheritance, every combination needs its own subclass.
4. Flip-card deck
Click to flip. Say the answer before you flip.
5. Composition, aggregation or inheritance?
Classify each relationship. Ask: is it is-a or has-a? If has-a, can the part live on its own? Streaks of 3+ score double.
6. 45-second speed round: does the part survive?
After the code runs, can any variable still reach the part object? A wrong answer costs 3 seconds.
Expected output
Until the TODOs are done, the first test stops with an AttributeError.
Think about it
- Why does the Library create the Shelf objects itself instead of receiving them as parameters?
- Why must
add_member()receive an existing Member object instead of creating a new one from a name? - The shelves are stored in a private attribute and never returned. How does that protect the composition?
Check my code
Practical tasks
Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
Task 1: A car has an engine (composition)
Write Engine (horsepower, running, start(), stop()) and Car that creates its own Engine in its constructor. Car.drive() returns a message that depends on whether the engine is running. Explain why a Car is not a subclass of Engine.
Starter file (write your code where it says pass # your code here):
class Engine:
pass # your code here
class Car:
pass # your code here
# ---- tests ----
c = Car("BYD Seal", 308)
print(c.drive())
c.engine.start()
print(c.drive())
Expected output when your code is correct:
BYD Seal: start the engine first BYD Seal drives with 308 hp
Hint
Model solution
A car has an engine; it is not an engine. Inheritance models 'is a'; composition models 'has a'. Here the Engine is created and owned by the Car, so it is composition.
class Engine:
def __init__(self, hp):
self.hp = hp
self.running = False
def start(self):
self.running = True
def stop(self):
self.running = False
class Car:
def __init__(self, model, hp):
self.model = model
self.engine = Engine(hp)
def drive(self):
if not self.engine.running:
return f"{self.model}: start the engine first"
return f"{self.model} drives with {self.engine.hp} hp"
# ---- tests ----
c = Car("BYD Seal", 308)
print(c.drive())
c.engine.start()
print(c.drive())
Task 2: Teams and players (aggregation)
Players exist independently and can move between teams. Write Player(name, rating) and Team(name) with sign(player) (a player can be in only one team, so sign them out of any old team), release(player) and strength() (the average rating). Show that releasing a player does not delete them.
Starter file (write your code where it says pass # your code here):
class Player:
pass # your code here
class Team:
pass # your code here
# ---- tests ----
ana, ben, cai = Player("Ana", 82), Player("Ben", 75), Player("Cai", 90)
red, blue = Team("Red"), Team("Blue")
for p in (ana, ben): red.sign(p)
blue.sign(cai)
print(red.strength(), blue.strength())
blue.sign(ana)
print([p.name for p in red.players], [p.name for p in blue.players], ana.team.name)
red.release(ben)
print(ben.name, ben.team, red.strength())
Expected output when your code is correct:
78.5 90.0 ['Ben'] ['Cai', 'Ana'] Blue Ben None 0
Hint
Model solution
class Player:
def __init__(self, name, rating):
self.name = name
self.rating = rating
self.team = None
class Team:
def __init__(self, name):
self.name = name
self.players = []
def sign(self, player):
if player.team is not None:
player.team.release(player)
self.players.append(player)
player.team = self
def release(self, player):
if player in self.players:
self.players.remove(player)
player.team = None
def strength(self):
if not self.players:
return 0
return round(sum(p.rating for p in self.players) / len(self.players), 1)
# ---- tests ----
ana, ben, cai = Player("Ana", 82), Player("Ben", 75), Player("Cai", 90)
red, blue = Team("Red"), Team("Blue")
for p in (ana, ben): red.sign(p)
blue.sign(cai)
print(red.strength(), blue.strength())
blue.sign(ana)
print([p.name for p in red.players], [p.name for p in blue.players], ana.team.name)
red.release(ben)
print(ben.name, ben.team, red.strength())
Task 3: School, departments and teachers
Build a three-level model: a School owns its Departments (composition: created by school.add_department(name), and deleted with the school), while Teachers are created separately and assigned to departments (aggregation). Write school.find_teacher(name), school.headcount() (unique teachers, since a teacher can be in two departments) and school.close_department(name) that removes it but leaves its teachers existing. Explain which relationships are composition and which are aggregation.
Starter file (write your code where it says pass # your code here):
class Teacher:
pass # your code here
class Department:
pass # your code here
class School:
pass # your code here
# ---- tests ----
s = School("Lakeside IB")
cs, ma = s.add_department("CS"), s.add_department("Maths")
raut, li, wu = Teacher("Mr Raut"), Teacher("Ms Li"), Teacher("Dr Wu")
cs.assign(raut); cs.assign(wu); ma.assign(li); ma.assign(wu)
print(s.find_teacher("Dr Wu"), s.headcount())
s.close_department("CS")
print(list(s.departments), s.headcount(), raut.name)
Expected output when your code is correct:
['CS', 'Maths'] 3 ['Maths'] 2 Mr Raut
Hint
Model solution
School ◆── Department is composition: departments are created by the school and have no meaning without it. Department ◇── Teacher is aggregation: teachers exist independently, can belong to several departments, and survive when a department closes.
class Teacher:
def __init__(self, name):
self.name = name
class Department:
def __init__(self, name):
self.name = name
self.teachers = []
def assign(self, teacher):
if teacher not in self.teachers:
self.teachers.append(teacher)
class School:
def __init__(self, name):
self.name = name
self.departments = {}
def add_department(self, name):
d = Department(name)
self.departments[name] = d
return d
def find_teacher(self, name):
found = []
for d in self.departments.values():
for t in d.teachers:
if t.name == name:
found.append(d.name)
return found
def headcount(self):
return len({id(t) for d in self.departments.values() for t in d.teachers})
def close_department(self, name):
return self.departments.pop(name, None)
# ---- tests ----
s = School("Lakeside IB")
cs, ma = s.add_department("CS"), s.add_department("Maths")
raut, li, wu = Teacher("Mr Raut"), Teacher("Ms Li"), Teacher("Dr Wu")
cs.assign(raut); cs.assign(wu); ma.assign(li); ma.assign(wu)
print(s.find_teacher("Dr Wu"), s.headcount())
s.close_department("CS")
print(list(s.departments), s.headcount(), raut.name)
Learning objectives
By the end of this page you should be able to:
- Explain how objects can be designed from smaller component objects (has-a relationships).
- Distinguish between aggregation (the parts can exist independently of the whole) and composition (the parts are created, owned and destroyed with the whole).
- Represent association, aggregation and composition on UML class diagrams with the correct symbols and multiplicities.
- Construct classes that use composition and aggregation, including delegating work to component objects.
- Evaluate composition against inheritance as a way of reusing code.
Building objects from objects
Inheritance models is-a. Many relationships are has-a instead: a car has an engine, a library has members. The containing object (the whole) holds references to component objects (the parts) and delegates work to them: car.start() calls self.engine.start().
| Aggregation | Composition | |
|---|---|---|
| Relationship | has-a (weak) | part-of (strong) |
| Who creates the part? | usually created elsewhere and passed in | created by the whole, usually in its constructor |
| Can the part be shared? | yes: one member, many libraries | no: a room belongs to one house |
| If the whole is destroyed | the parts carry on | the parts are destroyed too |
| Coupling | loose | tight |
| UML | hollow diamond at the whole | filled diamond at the whole |
| Examples | Team and Player; Playlist and Song; Department and Professor | House and Room; Order and OrderLine; Book and Chapter |
In code
class Library:
def __init__(self, name, labels):
self.__shelves = [Shelf(l) for l in labels] # composition: created and owned here
self.__members = [] # aggregation: filled from outside
def add_member(self, member): # an existing Member is passed in
self.__members.append(member)
ana = Member("Ana") # Ana exists before any library
city = Library("City", ["A", "B"])
city.add_member(ana)
del city # the shelves go; Ana is still here
In Python and Java, an object is removed by the garbage collector when no references to it remain. Composition is therefore partly a design rule: keep the parts private, create them inside the whole, and never hand them out, so nothing else can keep them alive.
UML symbols
- Association: a plain line (a Teacher teaches Students).
- Aggregation: a line with a hollow diamond at the whole (Team ◇—— Player).
- Composition: a line with a filled diamond at the whole (House ◆—— Room). The multiplicity at the whole is always 1.
- Inheritance: a hollow triangle pointing at the superclass.
Favour composition over inheritance?
- Flexibility: parts can be swapped, even at run time (a new engine); an inherited parent is fixed.
- No class explosion: 3 engines × 2 wheel types × GPS or not needs 12 subclasses, but only 6 component classes and 1 Car.
- Looser coupling: the Car uses an engine only through its public methods.
- Inheritance is still right for genuine is-a relationships that share behaviour and need polymorphism.
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. Distinguish between aggregation and composition, using an example of each. [4]
2. A university is made up of departments, which close if the university closes. Each department employs professors, who may move to another university. Draw a UML class diagram showing these relationships, with multiplicities. [4]
3. Construct a class Car composed of an Engine that is created inside the Car's constructor. Car.start() should delegate to the engine's start() method. [4]
class Engine:
def start(self):
return "engine running"
class Car:
def __init__(self):
self.__engine = Engine() # composition
def start(self):
return self.__engine.start() # delegation4. Explain why a designer might choose composition rather than inheritance to reuse the code of an existing class. [3]
5. State whether each relationship is aggregation, composition or inheritance: (a) Playlist and Song; (b) Order and OrderLine; (c) Cat and Animal. [3]
6. In a composition relationship, outline what happens to the Room objects when their House object is deleted, and how the House class should be written to guarantee this. [3]