Skip to content
OOPs part 3
  • topic trick
  • December 6, 2021
  • 6:12 pm

What is Inheritance in Python? Explain Multiple Inheritance and Operator Overloading.

Picture of topic trick
topic trick
In Python, inheritance is a concept in which existing classes can be modified by a new class. Existing classes are called base classes and new classes are called derived classes. Python Multiple inheritance is when a class comes from more than one base class. Derived classes inherit all the features of their bases. In this tutorial, you will learn about the object-oriented programming (OOPs) concept with examples. Let's discuss how inheritance works in Python.

Table of Contents

Table of Contents

Introduction.

Good to Go

Hello, and welcome back to another exciting tutorial of the Object-Oriented Programming in Python series on “Operator Overloading, python multiple inheritance and Inheritance in Python”. You’ll learn about subclasses, types of inheritance in Python, multiple inheritance, and operator overloading with example.

If you aren’t following along, I would recommend you to go back where you left or start from here.


Inheritance in programming languages is similar to the concept of inheritance in biology. Every child inherits some traits from their parents. In the same way, a child class inherits attributes and methods from the parent class along with some members of its own.

Inheritance is supported by all Object-Oriented programming languages. There are multiple inheritances in Python which we will talk about later in this tutorial. Multiple inheritances are one of the things that make you fall in love with Python.

Inheritance in Python, Python Inheritance
Inheritance in Python

Think of Quadrilateral as the parent class of a quadrilateral with four sides. There are two child classes that derive from it, namely Square and Rectangle.

The properties of the Quadrilateral class are inherited by both classes. Additionally, both classes have some properties that are unique to them.

A parent class, base class, and super class are all one and the same, as are child classes, subclasses, derived classes, and inherited classes.

Inheritance In Python

Do not repeat yourself

Python 3 only uses new-style classes – prior to that, there were old-style classes. You can see them here.

Object classes are inherited by every class in new style classes. For instance:

>>> class A:
... pass
... 
>>> A.__bases__
(<class 'object'>,)
>>> 
>>> issubclass(A,object)
True
>>> 

Types of Inheritance In Python

Do not repeat yourself

Type of Inheritance in Python
Type of Inheritance in Python

In Python, there are five types of inheritance. The following examples will help us better understand each of them.

Python Simple Inheritance

When a child class inherits from exactly one parent class, it is called Simple Inheritance in python.

Consider the following example in which class B inherits class A and objects of class B invoke the method of class A.

>>> class A:
...     def method1(self):
...         print("I am from class A")
...
>>> class B(A):
...     pass
...
>>>
>>> b1 = B()
>>> b1.method1()
I am from class A

Python Multiple Inheritance

A child class that inherits from more than one parent class is known as Multiple Inheritances in Python.

C++ and Java doesn’t support multiple inheritance .Python implement this concept using Method Resolution Order(MRO). We will discuss this in detail later in the section.

Consider the example given below in which class C inherits from class A and B.

>>> class A():
...     def method1(self):
...         print('I am from class A')
...
>>> class B():
...     def method2(self):
...         print('I am from class B')
... 
>>> # Specify all the parent classes while declaring as commma 
>>> #separated list in ().
>>> 
>>> class C(A, B):
...     def __init__(self):
...         print('This is from class C')
...         self.method1()
...         self.method2()
... 
>>> c1  = C()
This is from class C
I am from class A
I am from class B

Python Multilevel Inheritance

When a child class inherits from parent class which in turn inherits from its parent class, it is called Multilevel Inheritance in Python.

Think about the example given under the section “Multiple inheritance in python”. Rewriting is the same as a multilevel inheritance.

>>> class A():
...     def method1(self):
...         print('I am from class A')
...
>>> class B(A):
...     def method2(self):
...         print('I am from class B')
... 
>>> class C(B):
...     def __init__(self):
...         print('This is from class C')
...         self.method1()
...         self.method2()
... 
>>> c1  = C()
This is from class C
I am from class A
I am from class B

Python Hierarchical Inheritance

If there is more than one child class of a parent class, it is called Hierarchical Inheritance in Python. Here the child classes are called siblings.

The following example illustrates how parent class A generates two child classes B and C.

>>> class A():
...     def method1(self):
...         print('I am from class A')
... 
>>> class B(A):
...     def __init__(self):
...         self.method1()
... 
>>> class C(A):
...     def __init__(self):
...         self.method1()
...
>>> b1 = B()
I am from class A
>>> c1 = C()
I am from class A

Python Hybrid Inheritance

If we combine two or more types of inheritance in Python, it is called Hybrid Inheritance.

Consider the example given below in which parent class A derives two-child class B and C (Hierarchical Inheritance) and then class D inherits class B and C (Multiple Inheritance).

>>> class A():
...     def methodA(self):
...         print('I am from class A')
...  
>>> class B(A):
...     def methodB(self):
...         print('I am from class B')
...  
>>> class C(A):
...     def methodC(self):
...         print('I am from class C')
...  
>>> class D(B,C):
...     def __init__(self):
...         print('I am class D')
...         self.methodA()
...         self.methodB()
...         self.methodC() 
...
>>> d1 = D()
I am class D
I am from class A
I am from class B
I am from class C

Method Resolution Order

The mechanism behind Multiple Inheritance

Method Resolution Order is a way or a set of rules that an interpreter uses to resolve a method or attribute in a class.

MRO makes sense when we have many parent classes and a child class invokes a method that is present in more than one parent class. In this scenario, the interpreter needs an algorithm to choose the right method.
For example,
>>> class A(): pass
>>> class B(A): pass
>>> class C(A): pass
>>> class D(B,C): pass
>>> class E(C,B): pass
>>> class F(D,E): pass
Inheritance Graph
Inheritance Graph

OLD STYLE MRO – Depth First Left to Right

The old style MRO(python 2.2 or less) uses DLR algorithm to resolve a method.

If we apply DLR on our example then MRO for a method in class F will be F->D->E->B->C->A . The interpreter will search for a method or attribute in this manner.

LIMITATION OF DLR ALGORITHM

Since B precedes C in D, but C precedes B in E therefore the method resolution order would be ambiguous for F . This ambiguity is not detected by DLR algorithm.

NEW STYLE MRO – C3 LINEARIZATION ALGORITHM

The new style MRO(python 2.3 or more) uses a C3 linearization algorithm to resolve a method.

C3 ALGORITHM

  • [C1,C2,C3…. CN] denotes a list of classes. C1 is the head and rest C2, C3…CN is the tail.
  • C + [C1,C2 … CN) = C C1 C2 … CN
  • Consider a class C inheriting multiple classes say C1, C2, C3 .. CN . Then linearization of C will be L[C].
    • the linearization of C is the sum of C plus the merge of the linearizations of the parents and the list of the parents.

    • L[C(C1….CN)] = C + merge(L[C1] … L[CN], C1 … CN)
    • Here merge,
      • take the head of the first list, i.e L[C1][0];
      • if this head is not in the tail of any of the other lists, then add it to the linearization of C and remove it from the lists in the merge,
      • else look at the head of the next list and take it, if it is a good head.
      • Then repeat the operation until all the classes are removed or it is impossible to find good heads.
      • In this case, it is impossible to construct the merge, Python will raise an exception.
  • To find the MRO of a class in python class_name.mro() method is used.

Using the C3 algorithm the previous example will throw an error

Traceback (most recent call last):
File “”, line 1, in
TypeError: Cannot create a consistent method resolution
order (MRO) for bases B, C

Operator Overloading

Using operators directly on objects

Operator Overloading is a method to give extra functionalities to an operator.

For example, the ‘+’ operator can be used to add two integers as well as to concatenate two strings because the ‘+’ operator is overloaded by int and string class.

In Python, operator overloading is implemented using a predefined dunder method for every operator. The list of every dunder method is given below:-

Operator Method Name
+
__add__(self,other)
–
__sub__(self,other)
*
__mul__(self,other)
/
__truediv__(self,other)
//
__floordiv__(self,other)
%
__mod__(self,other)
**
__pow__(self,other)
>>
__rshift__(self,other)
<<
__lshift__(self,other)
&
__and__(self,other)
|
__or__(self,other)
^
__xor__(self,other)
+=
__iadd__(self,other)
-=
__isub__(self,other)
*=
__imul__(self,other)
/=
__itruediv__(self,other)
//=
__ifloordiv__(self,other)
%=
__imod__(self,other)
**=
__ipow__(self,other)
>>==
__irshift__(self,other)
<<==
__ilshift__(self,other)
&==
__iand__(self,other)
|==
__ior__(self,other)
^==
__ixor__(self,other)
<
__lt__(self,other)
>
__gt__(self,other)
<=
__le__(self,other)
>=
__ge__(self,other)
==
__eq__(self,other)
!=
__ne__(self,other)

For Example:

>>> class Point():
...     def __init__(self,x,y):
...             self.x = x
...             self.y = y
...     def __mul__(self,other):
...             return self.x * other.y - self.y*other.x
... 
>>> 
>>> p1 = Point(1,2)
>>> p2 = Point(3,4)
>>> p1*p2
-2
>>> 

In this example, we create a point class that contains two instance variables x and y coordinate. Here, we overload ‘*’ operator on objects of point class as Cross Product of two vectors with one end as the origin.

Conclusion.

Here’s a quick recap of what we covered in today’s OOPs tutorial. We learned about inheritance and its types. Additionally, we discover more about the resolution order. Finally, we learn how to implement operator overloading in Python using built-in methods.

If you have any feedback or suggestions, please let us know. We look forward to hearing from you.

person holding pencil near laptop computer
Database Technology
topictrick
Understanding IMS Databases: Functionality and Operation
Read More »
topictrick 18th November 2024
brown wooden i love you print board on green grass during daytime
WiFi Extenders
topictrick
How to Reset Netgear N300 WiFi Extender
Read More »
topictrick 2nd January 2024
Irish Driving License
How To Guide
topictrick
Driving Test Ireland: A Comprehensive Guide to Earning Your License
Read More »
topictrick 9th June 2023