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 browser1# 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).