Aggregation Example in Python

Pass an existing object in. The other class uses it; it does not create it.

IntermediateObject-Oriented ProgramsExample 16 of 25
aggregation-example.py
Run in browser
1# Program to demonstrate aggregation
2
3class Team:
4 def __init__(self, name):
5 self.name = name
6
7class Player:
8 def __init__(self, name, team: Team):
9 self.name = name
10 self.team = team
11
12t = Team("Tigers")
13p = Player("Alice", t)
14
15print(p.name, "plays for", p.team.name)

Output

Alice plays for Tigers

What's going on

The Player has a reference to a Team that may outlive or be shared with other players (aggregation).