Open In App

Python OOPS – Aggregation and Composition

Last Updated : 17 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

 

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.

 

Syntax: 

# Parent class
class Parent :        
           # Constructor
           # Variables of Parent class

           # Methods
           ...

# Child class inheriting Parent class 
class Child(Parent) :  
           # constructor of child class
           # variables of child class
           # methods of child class

           ...

Concept of Composition

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

  • It indicates a relationship component.
  • Both entities are dependent on each other in composition.
  • The composed object cannot exist without the other entity when there is a composition between two entities.

Python3




# Code to demonstrate Composition
  
# Class Salary in which we are
# declaring a 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
  
  
# Class EmployeeOne which does not 
# inherit the class Salary yet we will
# use the method annual salary using
# Composition
class EmployeeOne:
    def __init__(self, name, age, pay, bonus):
        self.name = name
        self.age = age
  
        # Making an object in which we are
        # calling the Salary class
        # with proper arguments.
        self.obj_salary = Salary(pay, bonus)  # composition
  
    # Method which calculates the total salary
    # with the help of annual_salary() method
    # declared in the Salary class
    def total_sal(self):
        return self.obj_salary.annual_salary()
  
# Making an object of the class EmployeeOne
# and providing necessary arguments
emp = EmployeeOne('Geek', 25, 10000, 1500)
  
# calling the total_sal method using 
# the emp object
print(emp.total_sal())


Output:

121500

Now as we can see in the above code we have successfully called the method of a completely different class inside another class that does not inherit the class using the concept of Composition. 

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.

Drawback of Composition

As we saw in the previous snippet, we are creating an object of the Salary class inside EmployeeOne class which has no relation to it. So from the outside, if we delete the object of EmployeeOne class i.e emp in this case, then the object of Salary class i.e obj_salary will also be deleted because it completely depends upon the EmployeeOne class and its objects. To solve this dependency problem, Aggregation came into the picture. 

Why we should use Aggregation over Composition?

Let’s take an example of both Composition and Aggregation to see the difference between them, and understand both precisely.

  • In the case of Composition, if we delete the object emp then the object of the Salary class which we initialized inside the EmployeeOne class will be deleted automatically because it is completely dependent upon the object of EmployeeOne class, so it might cause some error in the output code. 
    But in the case of Aggregation, we can see that we have created completely two different objects emp and salary, and passed the salary object as a parameter to the EmployeeOne class, so even if we delete the emp object, the object of the Salary class will remain the same and we can also use that elsewhere.
  • In the case of Composition, the objects were interdependent on each other, but in Aggregation, they are Unidirectional means that as salary is a completely independent object we can only pass salary to the emp, not vice versa.
  • Composition is defined by the PART-OF relationship which means that one object IS PART-OF ANOTHER OBJECT, but Aggregation is defined by the HAS-A relationship which means that one object HAS-A RELATION with another object.


Similar Reads

Python - Maximum Aggregation Pair in List
Sometimes, we need to find the specific problem of getting the pair which yields the maximum sum, this can be computed by getting initial two elements after sorting. But in some case, we don’t with to change the ordering of list and perform some operation in the similar list without using extra space. Let’s discuss certain ways in which this can be
3 min read
Aggregation in MongoDB using Python
MongoDB is free, open-source,cross-platform and document-oriented database management system(dbms). It is a NoSQL type of database. It store the data in BSON format on hard disk. BSON is binary form for representing simple data structure, associative array and various data types in MongoDB. NoSQL is most recently used database which provide mechani
2 min read
Python MongoDB - $group (aggregation)
MongoDB is an open-source document-oriented database. MongoDB stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. In this article, we will see the use of $group in MongoDB using Python. $group operation In PyMongo, the Aggregate Method is mainly used to process data records from multiple
3 min read
Inheritance and Composition in Python
Prerequisite - Classes and Objects in Python This article will compare and highlight the features of is-a relation and has-a relation in Python. What is Inheritance (Is-A Relation)? It is a concept of Object-Oriented Programming. Inheritance is a mechanism that allows us to inherit all the properties from another class. The class from which the pro
4 min read
Function Composition in Python
Prerequisite: reduce(), lambda Function composition is the way of combining two or more functions in such a way that the output of one function becomes the input of the second function and so on. For example, let there be two functions "F" and "G" and their composition can be represented as F(G(x)) where "x" is the argument and output of G(x) funct
4 min read
Implementation of Composition (Has-A Relation) in Python
We can access the member of one class inside a class using these 2 concepts: By Composition(Has-A Relation)By Inheritance(Is-A Relation) Here we will study how to use implement Has-A Relation in Python. Implementation of Composition in Python By using the class names or by creating an object we can access the member of one class inside another clas
3 min read
__invert__ and __abs__ magic functions in Python OOPS
The __invert__ and __abs__ magic methods are used for implementing unary operators in Python. In this article, we will see the concept of __invert__ and __abs__ magic functions in Python. __invert__() Magic Function in PythonThe __invert__ magic function is used to define the behavior of the bitwise NOT operation (~). When this method is implemente
4 min read
Pyspark - Aggregation on multiple columns
In this article, we will discuss how to perform aggregation on multiple columns in Pyspark using Python. We can do this by using Groupby() function Let's create a dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and
3 min read
Groupby without aggregation in Pandas
Pandas is a great python package for manipulating data and some of the tools which we learn as a beginner are an aggregation and group by functions of pandas. Groupby() is a function used to split the data in dataframe into groups based on a given condition. Aggregation on other hand operates on series, data and returns a numerical summary of the d
4 min read
Write custom aggregation function in Pandas
Pandas in python in widely used for Data Analysis purpose and it consists of some fine data structures like Dataframe and Series. There are several functions in pandas that proves to be a great help for a programmer one of them is an aggregate function. This function returns a single value from multiple values taken as input which are grouped toget
4 min read
Practice Tags :