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
1# Program to demonstrate aggregation23class Team:4 def __init__(self, name):5 self.name = name67class Player:8 def __init__(self, name, team: Team):9 self.name = name10 self.team = team1112t = Team("Tigers")13p = Player("Alice", t)1415print(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).
After this program
If the idea is still fuzzy, read Day 11: Classes and Objects in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 object-oriented programs, or see every topic on Python exercises.