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
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ 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
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read