Python Inheritance

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

What is Python Inheritance?

When a new class was created by inheriting functionalities called Child (or Derived or Sub Class). The class from which we inherit is called the Base, Parent, or Super.

Parent class

In Python object-oriented programming inheritance concept, the parent is the same as the normal class. It contains the attributes and methods that are common and reusable for a number of times. For example, in an organization, employee details like age, name, hire date, and gender are the same in every instance.

So, you can declare them in the parent and use them 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 children.

Child or derived class

It looks like a normal one, but it inherits (inheritance) all the attributes and methods available in its Python Parent Class (Derived From). You can also create new methods to perform the required calculations for this child.

In general, we can create this Child by passing the Parent Class as an object. It means creating a child along with parentheses.

Advantages of Python Inheritance

The following are the few advantages or benefits of using inheritance in Python object-oriented programming.

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

Let us see how to use this in real-time with multiple examples. You can also learn about the Python Multiple, Multilevel Inheritance, issubclass Method, and isinstance methods.

Python Class Inheritance Examples

In this example, we simply created a parent and a child (derived from the parent) with the 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 single inheritance. It means a single class inherits from a single parent. First, we declared an Employee with a variable x and func_msg() method.

Next, we created a Department that was inherited from the Employee. Within this Department class, we declared a variable of a = 250 and func_message().

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

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

    def func_message() # Child Method

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

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

    def func_message(self):
        print('Welcome to Department')
        print('This 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
--------------
250
Welcome to Department
This is inherited from Employee

Python Single Inheritance Analysis

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

Single Inheritance in Python Example 2

This single inheritance example shows how to use the Child object to access the parent functions and properties. For this example, we created a simple Employee with one method that prints a welcome message. Next, we created a Department child with a Program 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. As we already know, it is inherited from the Employee. You can access the Variables and methods in both the Employee and Department using this dept object.

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

Access Parent Variables from Child

In real-time, you might have to access or alter the variable values and methods of the parent from the Child. To access the Parent methods or properties from the Child inheritance, you must use the Python 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. And how to alter the variable values. First, we declared an employee with a variable of x = 10. Next, we declared the Department inherited from the Employee.

Within the Dept, we declared a variable of a = 250. Next, we called Employee variable x and added 22 (b = Employee.x + 22) to it.

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

    def func_message(self):
        print('Welcome to Department')
 
    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 Variables from Child output

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

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

Python Inheritance init Example

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

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')
         
    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)

Inheritance init output

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

Python Inheritance init Example 2

In this inheritance example, we are defining the init function in both the parent and the derived class. Within the derived one, 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()
At age 27 John is earning 650000
--------------
Jenny
At age 25 Jenny is earning 850005

init Example 3

Python inheritance is not about using the existing functions or attributes. You can extend or override them. In this 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 your name, age, and income. However, if you create an object of a Department, you have to provide your 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 child class inherited from another child. The following screenshot shows the diagrammatic representation of the Multilevel Inheritance.

Python Multilevel Inheritance 2

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

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

Multiple Inheritance in Python

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

Python Multiple Inheritance 1

In this Python Multiple Inheritance examples, we created two super classes, Main1 and Main2. Next, we created a child inherited from multiple parents.

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

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. So, instead of changing the logic in the parent class, you can define a new function in the child and write your own logic.

To override a method in Python Inheritance, you have to define a new method in the child with the same name and the same number of parameters.

In this example, we created the same method func_message() in both the Employee and Department (child). Next, we created an object for the employee and department and called the function name.

As you can see, the Employee object is printing the Welcome to Employee message because we haven’t changed anything in the parent. At the same time, the Department’s object is printing messages from child instead of printing base class messages. It is because we have overridden the func_message() definition in the child.

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

Python issubclass Method

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

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

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 isinstance method returns True if the Object (first argument) is the instance of the (second argument); otherwise, it returns false. The syntax of this special method is isinstance(Object, Class).

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

    def func_Derived(self):
        print('This is from Child')
         
mn = MainClass()
print(isinstance(mn, MainClass))
mn.func_message()

print('------------')
chd = Child()
print(isinstance(chd, Child))
print(isinstance(chd, MainClass))
print(isinstance(chd, ChildDerived))
chd.func_child()
chd.func_message()

print('------------')
dev = ChildDerived()
print(isinstance(dev, ChildDerived))
print(isinstance(dev, Child))
print(isinstance(dev, MainClass))
dev.func_child()
dev.func_message()
dev.func_Derived()

isinstance method output

True
Welcome to Main
------------
True
True
False
This is from Main
Welcome to Main
------------
True
True
True
This is from Main
Welcome to Main
This is from Child