Aggregation Example

Demonstrate aggregation where an object is passed in and shared rather than owned.

PythonIntermediate
Python
# Program to demonstrate aggregation

class Team:
    def __init__(self, name):
        self.name = name


class Player:
    def __init__(self, name, team: Team):
        self.name = name
        self.team = team


t = Team("Tigers")
p = Player("Alice", t)

print(p.name, "plays for", p.team.name)

Output

Alice plays for Tigers

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