Python Object & Class

Python Inheritance (With Examples)

Did you know that Python inheritance follows the same concept as an inheritance in living beings? It is one of the most crucial concepts in object-oriented programming and helps us create a relationship between two classes. It helps us direct the design of an application and determines how an application should grow when we add new features or when the requirements change. With the help of Python inheritance, we can create a new class without making any changes to an already existing class.

We refer to the new class as the derived (child) class, and the class from which it inherits is called the base (parent) class. A base class is also called a superclass. On the other hand, a derived class is also referred to as a subclass or subtype. In the Unified Modeling Language (UML), we represent inheritance as shown:

Python inheritance

                                                                                                                                                            Source: realpython.com

We show both the derived and base classes as boxes with the class name written towards the top. The relationship between the two classes is represented as an arrow pointing from the derived class to the base class.

Inheritance in Python

Let’s better understand the concept of Python inheritance through an example. Let’s say there exists a class “Fruit”, and you derive from it to create a new class called “Apple”. The simple relationship between the two classes says that “Apple” is a “Fruit”. 

The “Apple” class inherits the interface and implementation of the base class “Fruit”, such that Apple objects can replace Fruit objects without changing any of the desired properties in an application. This concept of substitution is called the Liskov substitution principle.

Types of Python Inheritance

There are two types of Python inheritance:

1. Single inheritance: In this type, a derived class inherits from only one base class.

Python inheritance

2. Multiple inheritance: In this inheritance, the derived class inherits from multiple base classes.

Python inheritance

3. Multi-level inheritance: In this, a derived class inherits another derived class.

Python inheritance

4. Hierarchical Inheritance: In this, we create more than one derived classes from one base class.

 

Python inheritance

 

We use the below syntax to create a Python inheritance:

                    

class baseClass:
class derivedClass(baseClass):

The derived class has all the features of its base class. However, we can add new features or modify the existing features in the derived class. Due to this feature of Python inheritance, we can reuse codes again and again in programming.

Example of Python inheritance:

                    

class shapes:
    def __init__(self, no_sides):
        self.n = no_sides
        self.sides = [0 for i in range(no_sides)]
 
    def takeSides(self):
        self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]
 
    def disSides(self):
        for i in range(self.n):
            print("Side",i+1,"is",self.sides[i]

In the above example, we created a class called “shapes” that has different attributes that will store the number of sides “n” and the value of each side in a list called “sides”.

The takeSides() method takes the value of each side, and the disSides() method displays these side lengths.

                    

class rec(shapes):
    def __init__(self):
        shapes.__init__(self,3)
 
    def findArea(self):
        a, b = self.sides
        # calculate the area
        area = (a + b) * 2
        print('The area of the rectangle is' %area)

In this code, we create a class “rec” (rectangle) that inherits from “shapes”. Now all the features of class shapes will be available in class “rec” without defining them again. However, we have added a new method findArea() which calculates the area of a rectangle based on the side values given.

Let’s look at a sample run:

                    

>>> t = rec()
 
>>> t.takeSides()
Enter side 1 : 6
Enter side 2 : 9
 
 
>>> t.disSides()
Side 1 is 6.0
Side 2 is 9.0
 
 
>>> t.findArea()
The area of the rectangle is 30.00

Through the example, we see that we did not have to define the methods takeSides() and disSides() for the class “rec” to be able to use them in the program. We observe this because when a feature is not found in the derived class (rec), the Python interpreter will search for it in the parent class (shapes) till it finds the attribute.

Method Overriding in Python

If you go back to the previous example, you will observe that we use the __init__() method in both the shapes and the rec class. We use the __init__() method in Python every time we want to create an object. When we do this, the child class (rec) will no longer inherit from the parent’s __init__() method. In other words, the derived __init__() method gets preference and overrides the base __init__() method.

We use this process of overriding to extend the definition of the class but not replace it. In the above example, we do this by calling the method in the base class from the one in the derived class ( we called shapes.__init__() from the rec __init__() method).

An easier way to make the subclass inherit all the methods and properties from its base class is to use the built-in super() function. 

                    

class rec(shapes):
    def __init__(self):
        super.__init__(3)
 
class rec(shapes):
    def __init__(self):
        shapes.__init__(self,3)

Both the __init__() method used in the above example gives us the same result. However, the super() function is preferred.

Questions and Answers

Q1. What is Python inheritance?

Answer. Inheritance is a mechanism through which we create a class or object based on another class or object. In other words, the new objects will have all the features or attributes of the class or object on which they are based. We refer to the created class as the derived or child class, and the class from which it inherits is the base or parent class.

Q2. Is inheritance possible in Python?

Answer. An object-oriented programming language like Python, not only supports inheritance but multiple inheritance as well. The mechanism of inheritance allows programmers to create a new class from a pre-existing class, which supports code reusability. We can also say that the methods defined in the parent class are reused in the child class.

Q3. What are the types of inheritance in Python?

Answer: Python inheritance is of four types:

  1. Single inheritance: In this type, a derived class inherits from only one base class.

Example:

                    

# Python program to show single inheritance
 
class a:
	def __init__(self):
			self.name = n
class b(a):
	def __init__(self):
			self.roll = roll

 

Class b inherits from class a.

  1. Multiple inheritance: In this inheritance, the derived class inherits from multiple base classes.

Example:

                    

# Python code to show the working of multiple 
# inheritance
class B1(object):
    def __init__(self):
        self.str1 = "Python1"
        print("B1")
  
class B2(object):
    def __init__(self):
        self.str2 = "Python2"        
        print("B2")
  
class derived(B1, B2):
    def __init__(self):
 

Class “derived” inherits attributes from both class B1 and B2.

  1. Multilevel inheritance: In this, a derived class inherits another derived class. There is no limit to the number of levels a multi-level inheritance we can archive in Python.

Example:

                    

# Python program to show
# multilevel inheritance
 
# The base class
class grandma:
 
	def __init__(self, grandmaname):
		self.grandmaname = grandmaname
 
# Middle class
class mother(grandma):
	def __init__(self, mothername, grandmaname):
		self.mothername = mothername
 
		# invoke a constructor of grandma class
		grandma.__init__(self, grandmaname)
 
# last class
class son(mother):
	def __init__(self,sonname, mothername, grandmaname):
		self.sonname = sonname
 
		# invoke a constructor of mother class
		father.__init__(self, mothername, grandmaname)
 
	def print_name(self):
		print('Grandma name :', self.grandmaname)
		print("Mother name :", self.mothername)
		print("Son name :", self.sonname)

In the above example, we derive the class son from class mother, which is in turn derived from class grandma.

  1. Hierarchical Inheritance: In this, we create more than one derived classes from one base class.

Example:

                    

#Python program to show
# hierarchical inheritance
 
 
# The base class
class parent:
      def funA(self):
          print("This function is in the parent class.")
 
# Derived class one
class child_one(parent):
      def funB(self):
          print("This function is in class child_one.")
 
# Derived class two
class child_two(Parent):
      def funC(self):
          print("This function is in class child_two.")

 

In the above example, we derive the classes: child_one and child_two from the base class “parent”.

Q4. Which inheritance is not supported in Python?

Answer: Unlike other object-oriented programming languages like Java, Python supports all types of inheritance, even multiple inheritance! And although C++ also supports this type of inheritance, it does not have the same sophisticated and well-designed approach as Python.

Python even supports Hybrid inheritance in which we implement more than one type of inheritance in one code.

Example:

                    

class a:
	def funcA(self):
		print(“Hello, you are now in class A”)
class b(a):
	def funcB(self):
		print(“Hello, you are now in class B”)
class c(a):
	def funcC(self):
		print(“Hello, you are now in class C”)
class d(c,a):
	def funcD(self):
		print(“Hello, you are now in class D”)
 
ref = d()
ref.funcD()
ref.funcC()
ref.funcA()

In the above code, we have implemented more than one type of inheritance. Classes a, b, and c implement hierarchical inheritance. On the other hand, classes a, c, and d implement multi-level inheritance.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Browse

Python Object & Class
  • Python Inheritance (With Examples)

Leave a Reply

Your email address will not be published. Required fields are marked *

Browse

Python Object & Class
  • Python Inheritance (With Examples)

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.