Aggregation Example

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

IntermediateTopic: Object-Oriented Programs
Back

Python Aggregation Example Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# 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

Understanding Aggregation Example

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

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents