Inheritance in Python
Introduction
In this blog, we will focus on Inheritance in python before going deep in oops you must be clear in the concept of classes and objects https://ainewgeneration.com/tag/oops/. Inheritance means one class has all the functionality of another class without having to write any of the same methods or attributes let’s go through it in more detail.
Table of Contents
- Inheritance in Python.
- Creating Parent Class.
- Creating Child Class.
- super() function.
- Multiple Inheritance in Python
- Method Resolution Order (MRO)
Inheritance in Python
Inheritance is the process in which one class inherits all the functionality from another class without having to create any of the same methods or variables.
Parent Class: The class from which all the methods and attributes are inherited is also known as a base class or Super class.
Child Class: The class which inheritance all the attributes and methods from the parents class or derived class.
Syntax of Python inheritance :
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Creating Parent Class
class Engineer:
def __init__(self, name, branch , years):
self.name = name
self.branch = branch
self.years = years
def branch(self):
return self.branch
def name(self):
return self.name
def years(self):
return self.years
def desc(self):
return (self.name,self.branch,self.years)
#Creating Objects
comp_eng = Engineer("rehan","CSE",2020)
mech_eng = Engineer("rohit","ME",2021)
print(comp_eng.desc())
print(mech_eng.desc())
output: ('rehan', 'CSE', 2020)
('rohit', 'ME', 2021)
Creating Child Class
Here in the below code, CSE is child class and Engineer is parent class. which CSE inheritance all the properties and methods from Engineer Class.
In the Below code, if you are not creating a constructor of child class i.e. CSE Class then the constructor of the parent class will be invoked automatically.
class CSE(Engineer):
pass
CS_1 = CSE("rehan","CSE",2020)
CS_1.desc()
output: ('rehan', 'CSE', 2020)
When you create a constructor of a child class i.e CSE Class then the constructor of the child class is invoked by default by creating an object of the child class.
super() function :
With the help of the super() function, you can access all the attributes and methods from the parents’ class. As Super() function creates a virtual object of parent class through which you can access all methods from super/parent class.
When you create an object of child class it will call init of child class first but if you have call super() then it will first call init of a parent class then call init child class.
class CSE(Engineer):
def __init__(self,name, branch , year, sec):
super().__init__(name, branch , years)
self.sec = sec
def desc_CS(self):
return ('rehan', 'CSE', 2020 ,"A")
CS_1 = CSE("rehan","CSE",2020 ,"A")
CS_1.desc_CS()
output: ('rehan', 'CSE', 2020 ,"A")
Multiple Inheritance in Python
In multiple inheritances, a child can inherit all features from multiple derived classes. The syntax is similar to single inheritances.
Syntax of Multiple Inheritance in Python :
class Base1:
pass
class Base2:
pass
class MultiDerived(Base1, Base2):
pass
Example of Multiple Inheritance :
# Parent class 1
class Employee:
def __init__(self, name, id):
self.name = name
self.id = id
# Parent class 2
class Employee_pay:
def __init__(self, pay, job_title):
self.pay = pay
self.job_title = job_title
# Deriving a child class from the two parent classes
class ML_Engineer(Employee, Employee_pay):
def __init__(self, name, id, pay, jobtitle, exp):
self.exp = exp
Employee.__init__(self, name, id)
Employee_pay.__init__(self, pay, jobtitle)
print("Name: {}, Pay: {}, Exp: {}".format(self.name, self.pay, self.exp))
TL = ML_Engineer('rehan', 113784, 150000, 'Machine Learning Engineer', 5)
output: Name: rehan, Pay: 150000, Exp: 5
Method Resolution Order (MRO)
When we have multiple inheritances it always starts from left to right. So __init__ method of child class will initiate first if it is not constructed in child class it will start the search from left to right to initialize the __init__ method of the base class.
It works similarly for methods if a specific method is searched It start searching first in the current class. if it is not found it starts searching in parents class i.e. from left to right order.
In the above code, the MultiDerived class search order will be [MultiDerived, Base 1, and Base 2]. this set of order sequences is called Method Resolution Order [MRO].
You can check MRO by using __mro__ attributes and mro() methods which python provides as you can see in the below code the sequence of MRO.
class A:
def create(self):
print(" Creating class A")
class B:
def create(self):
print(" Creating class B")
# Oder of classes
class AB(A, B):
def __init__(self):
print("Constructing AB")
ab = AB()
# Display the lookup order
print(AB.__mro__)
print(AB.mro())
output : Constructing AB
(<class '__main__.AB'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)
[<class '__main__.AB'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]
End Notes
I hope you are now clear On concepts of Inheritance in python. In the next blog, we will go more deeply into oops related to Encapsulation, Abstraction in python.