Concept of Aggregation

Aggregation is a concept in which an object of one class can own or access another independent object of another class. 

  • It represents Has-A’s relationship.
  • It is a unidirectional association i.e. a one-way relationship. For example, a department can have students but vice versa is not possible and thus unidirectional in nature.
  • In Aggregation, both the entries can survive individually which means ending one entity will not affect the other entity.

Python3




# Code to demonstrate Aggregation
  
# Salary class with the public method 
# annual_salary()
class Salary:
    def __init__(self, pay, bonus):
        self.pay = pay
        self.bonus = bonus
  
    def annual_salary(self):
        return (self.pay*12)+self.bonus
  
  
# EmployeeOne class with public method
# total_sal()
class EmployeeOne:
  
    # Here the salary parameter reflects
    # upon the object of Salary class we
    # will pass as parameter later
    def __init__(self, name, age, sal):
        self.name = name
        self.age = age
  
        # initializing the sal parameter
        self.agg_salary = sal   # Aggregation
  
    def total_sal(self):
        return self.agg_salary.annual_salary()
  
# Here we are creating an object 
# of the Salary class
# in which we are passing the 
# required parameters
salary = Salary(10000, 1500)
  
# Now we are passing the same 
# salary object we created
# earlier as a parameter to 
# EmployeeOne class
emp = EmployeeOne('Geek', 25, salary)
  
print(emp.total_sal())


Output:

121500

From the above code,  we will get the same output as we got before using the Composition concept. But the difference is that here we are not creating an object of the Salary class inside the EmployeeOne class, rather than that we are creating an object of the Salary class outside and passing it as a parameter of EmployeeOne class which yields the same result.

Python OOPS – Aggregation and Composition

In this article, we will compare and highlight the features of aggregation and Composition in Python OOPS.

 

Similar Reads

Concept of Inheritance

Inheritance is a mechanism that allows us to take all of the properties of another class and apply them to our own. The parent class is the one from which the attributes and functions are derived (also called as Base Class). Child Class refers to a class that uses the properties of another class (also known as a Derived class). An Is-A Relation is another name for inheritance....

Concept of Composition

Composition is a type of Aggregation in which two entities are extremely reliant on one another....

Concept of Aggregation

...

Drawback of Composition

Aggregation is a concept in which an object of one class can own or access another independent object of another class....

Why we should use Aggregation over Composition?

...

Contact Us