TowardsMachineLearning

Composition in Python

What is Composition:-

As the name implies , In composition one of the classes is “composed” of one or more instance of other classes.

In other words one class is container and other class is content and if you delete the container object then all of its contents objects are also deleted.

Composition models a “has a” relationship between “Composite” and “Component”.

Composition is represented through a line with a diamond at the composite class pointing to the component class. The composite side can express the cardinality of the relationship. The cardinality indicates the number or valid range of Component instances the Composite class will contain.

In the diagram above, the 1 represents that the Composite class contains one object of type Component. Cardinality can be expressed in the following ways:

  1. A number indicates the number of Component instances that are contained in the Composite.
  2. The * symbol indicates that the Composite class can contain a variable number of Component instances.
  3. A range 1..4 indicates that the Composite class can contain a range of Component instances. The range is indicated with the minimum and maximum number of instances, or minimum and many instances like in 1..*.

Don’t confuse Composition with Inheritance. Composition means that an object knows another object, and explicitly delegates some tasks to it. In simple words, Inheritance extends (inherits) a class, while Composition uses an instance of the class.

For example in the below example we’ve instantiated the Salary class using self.obj_salary and then using self.obj_salary  in the method total_salary inside the Employee class.

>>> class Salary:
        def __init__(self, pay, bonus): 
            self.pay=pay 
            self.bonus=bonus
        def annual_salary(self):
            return (self.pay*12) + self.bonus 
>>>  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.annual_salary()  
>>>  emp = Employee('max', 25, 15000, 10000)
>>>  print(emp.total_salary())  
output:-
    190000
 

In our example Employee class acts like Container and Salary class inside the Employee class acts like content in it. Composition represents part-of relationship. In our eg. Salary is part of Employee.

Article Credit:-

Name:  Praveen Kumar Anwla
6+ year of work experience

Leave a Comment