In previous part of this series, OOPs in Python Part 1, we discussed basic concepts of OOPs in Python. In this article, we will learn an essential concept of OOPs, i.e., Inheritance in Python, and its types with simple examples. Moreover, we will study Python overriding, issubclass method, and isinstance method.

Python Inheritance

Inheritance is one of the essential concepts of Python Object-Oriented programming techniques performed to achieve reuse of code. It is a mechanism to inherit new classes from existing classes and inherit their methods and attributes.

Let's start with some of the basic concepts.

Base class

In inheritance, a base class is the parent class or the super class. It can let its child classes inherit its methods and data fields depending their scope.

Derived class

A derived class is the child class that inherits methods and properties of the base class and can also have its own methods and properties. It is also called a subclass.

Syntax for Python inheritance

class BaseClass:
      Base class data fields and methods (parent class block)
class DerivedClass (BaseClass):
      Derived class data fields and methods (Child class block)

Example

class dog:          #Base class  
    Name = ‘Dommy’  
    Age = 3  
    Print(“My Pet Name is” +Name, “and current Age is:”+Age)  
class My_Pet(dos):  #Derived class  
    Color=’violet and blue’  
    Print(“My pet”,+Name, “color is:”+color)  

Benefits of Python Inheritance

Types of Inheritance in Python

In Python, there are five types of inheritances available.

  1. Single inheritance

  2. Multiple inheritance

  3. Hybrid inheritance

  4. Hirarchical inheritance

  5. Multilevle inheritance

We will discuss them one by one.

Python OOPs, Deep Dive Into Inheritance And Their Types

Single Inheritance

Single inheritance is considered as one child class that is derived from only one parent class only.

Python OOPs, Deep Dive Into Inheritance And Their Types

Syntax

class Base_class:
    <Base class statements>
class DerivedClass(Base_class):
    <Derived class statements>

Example

class parent:    
    def Dog(name):  #Base class  
        name=name    
        print("Dog name is:",name)    
        
class child(parent):  #Derived class  
    def puppy(self,name1):    
        self.name1=name1           
        print("Puppy name is:",name1)    
parent.Dog ('Boxer')    
        
obj=child()  #Create object for our child class  
obj.puppy ('Jimmy')  #To access child class method that can able to access Base class method also   

Output

Multilevel inheritance

When one class inherits from another class, each derived class will act as an intermediate base class to the next derived class. There is no limit for extending derived classes.

Python OOPs, Deep Dive Into Inheritance And Their Types

Syntax

class Base_class:
    <base class statements>
class derived_class1(Base_class):
    <Derived_class1, Base_class statements >
class derived_class2(derived_class1):
    <Base_class, derived_class1, derived_class2 statements>

Example

class class_A:                  #Base class   
    def grandfather(self):  
        gname='Raja'  
        print("Grandfather Name is:",gname)  
  
class class_B(class_A):         #Inteermediate Base class  
    def father(self):  
        fname='jhon'  
        print("Father Name is:",fname)  
  
class class_C(class_B):        #Derived class  
    def child(self):  
        cname='Chinna'  
        print("Child name is:",cname)  
  
C=class_C() #To create object for Derieved class 
C.grandfather() #To acces class A method by class C object
C.father()  #To access class B method by class C object
C.child()   

Output

Python OOPs, Deep Dive Into Inheritance And Their Types

Multiple inheritance

Python can support multiple inheritances, when a new derived class inherits features from more than one base classes. For example, a child can get attributes from his father and mother.

Python OOPs, Deep Dive Into Inheritance And Their Types

The syntax of multiple inheritance is given below.

Syntax

class base_A:
<class suit>
class base_B:
<class suit>
class derivedclass_C(base_A,base_B):
<class suit>

Example

class class_A():  #Base class A  
    def male(self,name,age):    
        self.name=name    
        self.age=age    
        print("The Male Name is: %s and Age is: %d" %(name,age))    
                
class class_B():  #Base class B  
    def female(self,name,age):    
        self.name=name    
        self.age=age    
        print("The Female Name is: %s and Age is: %d" %(name,age))    
        
class class_C(class_A,class_B):  #Derived class extended by Base classess A and B  
    def human(self,place1,place2):    
        self.place1=place1    
        self.place2=place2   
        print("Humans possible to live in: %s and Age is: %s" % (place1,place2))    
        
obj=class_C()    
obj.male('Chinna',21)#To access class A method by class C object  
obj.female('Bharathi',2)#To access class B method by class C object  
obj.human('Earth','Moon')       

Output

Hierarchical Inheritance

A hierarchical inheritance works well in python like other object-oriented languages. When more than one derived class extended from one base class consider as a hierarchical inheritance.

Python OOPs, Deep Dive Into Inheritance And Their Types

Syntax

class class_A:
    <Base class statements>
class class_B(class_A):
    <class_B and class_A statements>
class class_C(class_A):
    <class_C and class_A statements>

Example

class class_A:  #Base class
    def base():  
        print("This is a Base class")  
  
  
class class_B(class_A):#Derived class  
    def derived_1(self):        
        class_A.base()  
        print("This is a Derived class-1 ")  
  
  
class class_C(class_A):  #Derived class
    def derived_2(self):  
        class_A.base()  
        print("This is a Derived class-2")  
  
obj1=class_B()  #Create object1 for class B
obj2=class_C()  #Create object2 for class C
  
obj1.derived_1() #To handle class B and A properties  
obj2.derived_2() #To handle class C and A properties 

Output

Python OOPs, Deep Dive Into Inheritance And Their Types

Hybrid inheritance

Python provides us the hybrid inheritance for handling more than one type of inheritance in a program. A combination of more than one inheritance, multilevel and hierarchical inheritance work together (inherit its properties) in a program called as Hybrid inheritance.

Python OOPs, Deep Dive Into Inheritance And Their Types

Let’s see a syntax for hybrid inheritance.

Syntax

class class_A:
    <class-suit>
class class_B(class_A):
    <class-suit>
class class_C(class_B):
    <class-suit>
class class_D(class_B):
    <class-suit>

Example

class A:  #Base class 
    def summation(a,b):  
        return a+b  
  
class B(A):  #Intermediate base class B extended by class A (Base class)
      
    def subtract(a,b):  
        x=a-b  
        print("The subtract value is:",x)  
        print("Summation value is:",A.summation(20,30))  
          
  
class C(B):  #Derived class C extended by class B
      
    def multiplication(self,a,b):  
        B.subtract(10,20)  
        y=a*b  
        print("Multiplication value is:",y)  
  
class D(B):  #Derived class D extended by clas B
    def divide(self,a,b):  
        B.subtract(50,30)  
        z=a/b  
        print("Divide value is:",z)  
  
obj1=C()  
obj2=D()  
obj1.multiplication(10,20) # To access Class A, B and C 
print(" ")  
obj2.divide(30,5)# To access Class A, B and D 

Output

Python OOPs, Deep Dive Into Inheritance And Their Types

Python Method overriding

In method overriding, a derived class can override a method of a base class, and add more functionality to it.

Limitation of overriding

Example 1

class parent:    
    def display(self):    
        print("Befor override")  #Before override statment  
class child(parent):    
    def display(self):    
        print("After override")  #After override statement  
d = child()    
d.display()     

Here, we hve created two classes that simulate parent and child functionality.

Then also created two methods itself each that represented the same name such as display().

Next, I created an object for the child class that extended from the parent class.

When execute the print statement under the display() method, it will override the class parent statement and display that. Given below

Output

Python OOPs, Deep Dive Into Inheritance And Their Types

Example 2 - Realtime example of overriding

Let’s take a look at this simple example to clearly understand method overriding.

class car:  
    def car_color(self):  
        a='gray_color'  
        return a;  
class toyota(car):  
    def car_color(self): #override method of car class  
        b='black_color'  
        return b;  
class audi(car):  
    def car_color(self): #override method of toyota  
        c='blue_color'  
        return c;  
  
c1=car()  
c2=toyota()  
c3=audi()  
  
print("Mostly liked car color is:",c1.car_color())  
print("Toyata car color is:",c2.car_color())  
print("Audi car color is:",c3.car_color())  

Output

Python OOPs, Deep Dive Into Inheritance And Their Types

Python issubclass() method

The “issubclass()” method used to find the relationship of the specified classes. It will take an object and subclass name in the parameter to return output as True or False. If it returns True, we confirm the given an object is a subclass of the specified object. Otherwise False.

Example

class fruit1:  
    def apple(self):  
        a='green_color'  
        return a;  
class fruit2:  
    def lemon(self):  
        b='yello_color'  
        return b;  
class fruit3:  
    def blueberry(self):  
        c='Blue_color'  
        return c;  
class derived(fruit1,fruit2,fruit3):  
    def derived(sself):  
        d='RGB'  
        return d;  
  
d=derived()  
print(issubclass(derived,fruit1))   #Check the derived class issubclass of fruit1?  
print(issubclass(fruit1,fruit2))    #Check the fruit1 issubclass of fruit2?  
print(issubclass(derived,fruit3))   #Check the derived issubclass of fruit3?  

Output

Python OOPs, Deep Dive Into Inheritance And Their Types

Python isinstance() method

Python can be available to check the relationship between the objects and classes by using “isinstance()” method.

Example

class calculation1:  
    def add(self,x,y):  
        return x+y;  
class calculation2:  
    def sub(self,x,y):  
        return x-y;  
class derived(calculation2):  
    def divide(self,x,y):  
        return x/y;  
  
d=derived()  
c=calculation2()  
print(isinstance(d,derived)) #Check the object d isinstance of derived class
                               
print(isinstance(d,calculation1))#Check the object d isinstance of calculation1 class  
  
print(isinstance(d,calculation2))#Check the object d isinstance of calculation2  

Output

Python OOPs, Deep Dive Into Inheritance And Their Types

Summary

I hope, you understood very well about the Inheritance and its types. If you are getting any queries while doing above mentioned, feel free to comment below, and stay tuned, we will see the rest of OOPs concepts in the next article.