Have you heard the term aggregation or composition of classes in python? This can be a little tricky but let me share a simple scenario to explain the concept.

Let’s assume we have a class employee and another class salary. The salary class has capability to calculate annual salary given the pay and the bonus.

So let’s create the salary class in python

class Salary:
def __init__(self, pay, bonus):
self.pay = pay
self.bonus = bonus

def anual_salary(self):
return (self.pay*12) + self.bonus

In the salary class we can see it takes the pay and bonus and initialized those variables in the __init__ method. The anual_salary method of the salary class calculates the annual salary by multiplying the pay by 12 and adding the bonus to it. The pay is the monthly pay so 12 is for the number of months in a year.

Now lets create a class employee and use the principle of composition between employee and salary class.

class Employee:
def __init__(self, name, age, pay, bonus):
self.name = name
self.age = age
self.obj_salary = Salary(pay, bonus)

def total_salary(self):
return self.obj_salary.anual_salary()

In the above employee class, we created an object of the salary class in the __init__.  self.obj_salary = Salary(pay, bonus). So we are saying the salary class is part of the Employee class and you can see the method total_salary of the employee class uses the salary object to call the public method anual_salary from the salary class.

So now we can create an instance of the employee class and be able to get the annual salary as show below.

 

Now what then is aggregation? Let’s  rewrite the employee class using aggregation and explain.

class Employee:
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.obj_salary = salary

def total_salary(self):
return self.obj_salary.anual_salary()

In this new Employee class, we see the __init__ method takes a salary object directly and the total_salary method of the employee class used that object to get the annual salary. This type of relationship is described as ‘Has – a’. It reads the employee has a salary. But don’t get it confused as a salary has an employee because the association between the classes is uni dirrectional as in one direction. The objects of these class are independent because they live on their own and can survive even after deleting one of them. Lets see this in action how to execute the code for the aggregation.

We can see now we created a salary object first and pass it to an employee object. These two objects are independent which means even when the salary object dies the employee object will still survive and work on its own. This is aggregation and its different from composition. This concept is applied when you are not doing inheritance for the class.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *