Python OOPS - Aggregation and Composition
Last Updated :
17 May, 2024
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
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
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
3 min read
Grouping and Aggregating with Pandas
When working with large datasets it's used to group and summarize the data to make analysis easier. Pandas a popular Python library provides powerful tools for this. In this article you'll learn how to use Pandas' groupby() and aggregation functions step by step with clear explanations and practical
3 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:Python3 # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql i
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 propertie
4 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 se
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 mult
4 min read
Pandas Groupby: Summarising, Aggregating, and Grouping data in Python
GroupBy is a pretty simple concept. We can create a grouping of categories and apply a function to the categories. Itâs a simple concept, but itâs an extremely valuable technique thatâs widely used in data science. In real data science projects, youâll be dealing with large amounts of data and tryin
4 min read
Function Composition in Python
Function composition is a powerful concept where two or more functions are combined in such a way that the output of one function becomes the input for the next. It allows for the creation of complex functionality from simple, reusable building blocks. This concept is widely used in functional progr
6 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read