Implementation of Composition (Has-A Relation) in Python
We can access the member of one class inside a class using these 2 concepts:
- By Composition(Has-A Relation)
- By Inheritance(Is-A Relation)
Here we will study how to use implement Has-A Relation in Python.
Implementation of Composition in Python
By using the class names or by creating an object we can access the member of one class inside another class.
class Engine: # engine specific functionality ''' ''' ''' class Car: e = Engine() e.method1() e.method2() ''' '''
In these above example class Car has-A Engine class reference. Here inside class Car also we can create different variables and methods. Using object reference of Engine class inside Car class we can easily access each and every member of Engine class inside Car class.
Example 1: Executable code for composition
Name of Employee : Ronil Age of Employee : 20 Address of Employee : Indore Salary of Employee : 25000
Here in the above example, we have 2 classes ‘Employee’ and ‘Data’. Inside ‘Data’ class Constructor we are creating an object of Employee class due to which we can access the members of the Employee class easily. Inside the Data class Employee class object becomes an instance variable of “Data” class. We are creating objects inside the constructor so whenever we will call any method or variable of class Employee we must use self keyword. We can replace “self.emp_obj” to “Employee”, but by using the class name Employee we can access only the static method or variable of the Employee class.
Example 2: Another simple example using Composition
Class - B Constructor. Class - A Constructor M1 method of Class - A. M2 method of Class - B.
Here in the above example, we are creating an object of class A inside instance method of class B that is m2() method. So the flow of execution will be Initially, the object of class B will be created so the constructor of class B will get executed. Now object of class B is calling m2() method, so the cursor will go to the m2() method of class B. Inside the m2() method of class B object of class A is created so the constructor of class A will be executed then m1() method of class A will be executed finally it will print the final statement of m2() method and execution end’s here.