Python Inheritance

Inheritance is an interesting and important concept in the Object-Oriented Programming Language. Python inheritance means creating a new class that inherits (takes) all the functionalities from the parent class and allows them to add more.

The Python new class that we created by inheriting functionalities called Child Class (or Derived Class or Sub Class). The class from which we inherit called the Python Base Class or Parent Class or Super Class.

  • Parent Class: This is the same as the normal class. It contains the attributes and methods that are common and reusable for the number of times. For example, in an organization, employee details like age, name, hire date, gender is the same in every instance. So, you can declare them in the parent class and use it in the child classes. Similarly, some calculations like the Salary Hike percentage might be the same. So, we can define a function in the parent class for one time, and you can call it from multiple child classes.
  • Child Class: Looks like a normal class. It inherits all the attributes and methods that are available in its Python Parent Class (Derived From). Apart from that, you can create new methods to perform the required calculations for this child class. In Python, we can create this Child class by passing the Parent Class as an object while creating a class. It means, creates a child class along with parentheses.

Advantages of Inheritance in Python

The following are the few advantages or benefits of using inheritance in Python.

  • Python Inheritance provides Code reusability, readability, and scalability.
  • Python Inheritance reduces the code repetition. You can place all the standard methods and attributes in the parent class. These are accessible by the child class derived from it.
  • By dividing the code into multiple classes, the applications look better, and the error identification is easy.

Let us see how to use Inheritance in Python with multiple examples. Along with this, you can learn about the Python Multiple Inheritance, Multilevel Inheritance, issubclass Method, and isinstance methods.

Python Class Inheritance Examples

In this Python class inheritance example, we simply created a parent class and a child class (derived from the parent class) with pass keyword. You can consider this as the syntax of this Python class Inheritance.

class Employee:
    pass
 
class Department(Employee):
    pass

Single Inheritance in Python

It is an example of a single inheritance in python. It means a single class derived from a single parent class. First, we declared an Employee class with a class variable x and func_msg() method. Next, we created a Department class that inherited from the Employee class. Within this Department class, we declared a class variable of a = 250 and func_message().

class Employee:
    x = 10 # Parent class Variable
 
    def func_msg() # Parent class Method
 

class Department(Employee):
    a = 250 # Child class Variable

    def func_message() # Child class Method

It is an extension to the above single inheritance in python example. Instead of defining empty methods, we used the print function to print a message from the Employee and Department classes.

class Employee:
    x = 10 
 
    def func_msg(self):
         print('Welcome to Employee Class')
 
class Department(Employee):
    a = 250

    def func_message(self):
        print('Welcome to Department Class')
        print('This class is inherited from Employee')
 
emp = Employee()
print(emp.x)
emp.func_msg()
 
print('--------------')
dept = Department()
print(dept.a)
dept.func_message()

Python Single Inheritance output

10
Welcome to Employee Class
--------------
250
Welcome to Department Class
This class is inherited from Employee

Python Single Inheritance Analysis

  • emp = Employee() creates an instance or Object of the Employee class. Using this Object name, we can access the functions and properties of the Employee class.
  • print(emp.x) – prints the employee class variable value x i.e., 10.
  • emp.func_msg() – prints the message Welcome to Employee Class
  • dept = Department() – It creates an object of the Department Class. 
  • print(dept.a) – prints the Department class variable value a I.e., 250.
  • dept.func_message() – prints the message from the department class method func_message()

Single Inheritance in Python Example 2

In this Python single inheritance example, we show how to use the Child class object to access the parent class functions and properties. For this Python inheritance example, we created a simple Employee class with one method that prints a welcome message. Next, we created a Department child class with a Python pass keyword.

class Employee:
 
    def func_msg(self):
        print('Welcome to Employee Class')
 
class Department(Employee):
    pass
 
emp = Employee()
emp.func_msg()
 
print('--------------')
dept = Department()
dept.func_msg() # Calling Parent Method
Python Inheritance 4

dept = Department() – It creates an object of the Department Class. As we already know, it inherited from the Employee class. You can access the Variables and methods in both the Employee Class and Department Class using this dept object.

dept.func_msg() – It calls the func_msg() present in the parent class.

Access Parent Class Variables from Child Class in Python

In real-time, you might have to access or alter the variable values, methods of the parent class from the Child Class. To access the Parent Class methods or properties from the Child Class, you have to use the Class name and the dot operator. For instance, ParentClassName.VariableName or ParentClassName.MethodName()

In this Python inheritance example, we show how to access the Parent class variables from the child class. And, how to alter the variable values. First, we declared an employee class with a class variable of x = 10. Next, we declared the Department Class inherited from Employee Class. Within the Dept class, we declared a class variable of a = 250. Next, we are calling Employee class variable x and added 22 (b = Employee.x + 22) to it.

class Employee:
    x = 10 
 
    def func_msg(self):
        print('Welcome to Employee Class')
 
class Department(Employee):
    a = 250
    b = Employee.x + 22 

    def func_message(self):
        print('Welcome to Department Class')
 
    def func_changed(self):
        print('New Value = ', Employee.x + 449)
 
emp = Employee()
print(emp.x)
emp.func_msg()
 
print('--------------')
dept = Department()
print(dept.a)
print(dept.b)
dept.func_message()
dept.func_changed()

Access Parent Class Variables from Child Class output

10
Welcome to Employee Class
--------------
250
32
Welcome to Department Class
New Value =  459

As you can see, printing x from the Employee object returns 10. However, b from department object is returning 10 (Employee.x))+ 22 = 32.

Python Inheritance init Example

Until now, we have created the Derived classes that inherit the methods and the variables of the Python parent class. In this Python inheritance init example, we define the init function in the parent class and use those values inside the parent class function. Here, we declared a child class with the pass keyword. Next, we created an object of the Department class and called those parent functions.

class Employee:
 
    def __init__(self, fullname, age, income):
        self.fullname = fullname
        self.age = age
        self.income = income
 
    def func_msg(self):
        print('Welcome to Employee Class')
         
    def func_information(self):
        print('At age', self.age, self.fullname, 'is earning', self.income)
 
class Department(Employee):
    pass
 
emp = Employee('Suresh', '27', '650000')
emp.func_msg()
emp.func_information()
 
print('--------------')
dept = Department('Jenny', '25', '850005')
dept.func_msg() # Calling Parent Method func_msg(self)
dept.func_information() # Calling Parent Method func_information(self)

Python Inheritance init output

Welcome to Employee Class
At age 27 Suresh is earning 650000
--------------
Welcome to Employee Class
At age 25 Jenny is earning 850005

Python Inheritance init Example 2

In this Python Inheritance example, we are defining the init function in both the parent class and the derived class. Within the derived class, Employee.__init__(self, fullname, age, income) to inherit the functionality of the parent class Employee.

class Employee:
 
    def __init__(self, fullname, age, income):
        self.fullname = fullname
        self.age = age
        self.income = income
         
    def func_information(self):
        print('At age', self.age, self.fullname, 'is earning', self.income)
 

class Department(Employee):
     
    def __init__(self, fullname, age, income):
         Employee.__init__(self, fullname, age, income)
 

emp = Employee('John', '27', '650000')
emp.func_information()
 
print('--------------')
dept = Department('Jenny', '25', '850005')
print(dept.fullname)
dept.func_information()

class Inheritance init example 2 output

At age 27 John is earning 650000
--------------
Jenny
At age 25 Jenny is earning 850005

Python Inheritance init Example 3

The python inheritance is not about using the existing functions or attributes. You can extend or override them. In this Python inheritance example, we are adding another parameter called dept_name inside the Department init.

It means when you create an object of the Employee class, you have to provide name, age, and income. However, if you create an object of Department, you have to provide name, age, income, and Department Name.

class Employee:
 
    def __init__(self, fullname, age, income):
        self.fullname = fullname
        self.age = age
        self.income = income
         
    def func_information(self):
        print('At age', self.age, self.fullname, 'is earning', self.income)
 
class Department(Employee):
     
    def __init__(self, fullname, age, income, dept_name):
        Employee.__init__(self, fullname, age, income)
        self.dept_name = dept_name
 
    def func_info(self):
        print(self.fullname, self.age, 'Working as a',
               self.dept_name, 'is earning', self.income)

emp = Employee('John', '27', '650000')
emp.func_information()
 
print('--------------')
dept = Department('Jenny', '25', '850005', 'Developer')
dept.func_information()
dept.func_info()
At age 27 John is earning 650000
--------------
At age 25 Jenny is earning 850005
Jenny 25 Working as a Developer is earning 850005

Multilevel Inheritance in Python

Python allows you to create a Multilevel inheritance. It means the Python child class inherited from another child class. The following screenshot shows the diagrammatic representation of the Python Multilevel Inheritance.

Python Inheritance 2

In this example of Multilevel Inheritance in Python, first, we created a Main class with one method. Next, we created a Child class that inherited from the Main class. Next, we created another ChildDerived class derived from the Child class (already inherited from MainClass).

class MainClass:
     
    def func_message(self):
        print('Welcome to Main Class')
 
class Child(MainClass):
 
    def func_child(self):
        print('Welcome to Child Class')
        print('This class is inherited from Main Class')
 
class ChildDerived(Child):
 
    def func_Derived(self):
        print('Welcome to Derived Class')
        print('This class is inherited from Child Class')
         
print('------------')
chldev = ChildDerived()
chldev.func_Derived()
 
print('------------')
chldev.func_child()
 
print('------------')
chldev.func_message()

Multilevel inheritance output

------------
Welcome to Derived Class
This class is inherited from Child Class
------------
Welcome to Child Class
This class is inherited from Main Class
------------
Welcome to Main Class

Multiple Inheritance in Python

The Python Programming language allows you to use multiple inheritances. It means a child class can inherit from multiple classes at the same time. Let me show you the diagrammatic representation of the Python Multiple Inheritance.

Python Inheritance 1

In this Python Multiple Inheritance example, we created two superclasses MainClass1 and MainClass2. Next, we created a child class inherited from both those classes.

class MainClass1:
         
    def func_main1(self):
        print('This Welcome Message is from Main Class 1')
 
class MainClass2:
         
    def func_main2(self):
        print('This is an another Message coming from Main Class 2')
         
class ChildClass(MainClass1, MainClass2):
     
    def func_child(self):
        print('This is coming from Child Class')
 
chd = ChildClass()
 
chd.func_main1()
chd.func_main2()
chd.func_child()

Multiple inheritance output

This Welcome Message is from Main Class 1
This is an another Message coming from Main Class 2
This is coming from Child Class

Method Overriding in Python Inheritance

In real-time, you might need to change the program logic of a method defined in the parent or base class. However, changing that might affect the remaining classes inherited from that parent class. So, instead of changing the logic in the parent class, you can define a new function in the child class and write your own logic. To override a method in Python Inheritance, you have to define a new method in the child class with the same name and the same number of parameters.

In this Python inheritance example, we created the same method func_message() in both the Employee and Department (child) class. Next, we created an object for the employee class and department class and called the function name. As you can see, Employee object is printing the Welcome to Employee Class message because we haven’t changed anything in the parent class. Whereas, Department object is printing messages from child class instead of printing base class message. It is because we have overridden the func_message() definition in the child class.

class Employee:
     
    def func_message(self):
        print('Welcome to Employee Class')
 
class Department(Employee):
 
    def func_message(self):
        print('Welcome to Department Class')
        print('This class is inherited from Employee')
 
emp = Employee()
emp.func_message()
 
print('------------')
dept = Department()
dept.func_message()

Method Overriding in Inheritance output

Welcome to Employee Class
------------
Welcome to Department Class
This class is inherited from Employee

Python issubclass Method 

The Python issubclass method accepts two arguments, and they are subclass (child class) and superclass (Main Class). The Python issubclass method is to check whether the sub class inherited from a superclass or not, and returns boolean True or False based on the result. The syntax of this Python issubclass method is: issubclass(sub, sup)

class MainClass:
     
    def func_message(self):
        print('Welcome to Main Class')
 
class Child(MainClass):
 
    def func_child(self):
        print('This class is inherited from Main Class')
 
class ChildDerived(Child):
 
    def func_Derived(self):
        print('This class is inherited from Child Class')
         
print(issubclass(ChildDerived, Child))
print(issubclass(ChildDerived, MainClass))
 
print('------------')
print(issubclass(Child, MainClass))
 
print('------------')
print(issubclass(Child, ChildDerived))

Python issubclass function output

True
True
------------
True
------------
False

Python isinstance Method 

The Python isinstance method also accepts two arguments, and they are Object Name and the Class Name. This Python isinstance method returns True if the Object (first argument) is the instance of the Class (second argument); otherwise, it returns false. The syntax of this Python isinstance method is: isinstance(Object, Class).

class MainClass:
     
    def func_message(self):
        print('Welcome to Main Class')
 
class Child(MainClass):
 
    def func_child(self):
        print('This class is inherited from Main Class')
 
class ChildDerived(Child): 

    def func_Derived(self):
        print('This class is inherited from Child Class')
         
mn = MainClass()
print(isinstance(mn, MainClass))
 
print('------------')
chd = Child()
print(isinstance(chd, Child))
print(isinstance(chd, MainClass))
print(isinstance(chd, ChildDerived))
 
print('------------')
dev = ChildDerived()
print(isinstance(dev, ChildDerived))
print(isinstance(dev, Child))
print(isinstance(dev, MainClass))

Python isinstance method output

True
------------
True
True
False
------------
True
True
True