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. 

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