The Wayback Machine - https://web.archive.org/web/20241124025158/https://www.geeksforgeeks.org/multiple-inheritance-in-python/
Open In App

Multiple Inheritance in Python

Last Updated : 22 Feb, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Inheritance is the mechanism to achieve the re-usability of code as one class(child class) can derive the properties of another class(parent class). It also provides transitivity ie. if class C inherits from P then all the sub-classes of C would also inherit from P.
 

Multiple Inheritance 
When a class is derived from more than one base class it is called multiple Inheritance. The derived class inherits all the features of the base case.
 

Multiple Inheritance

 

Syntax:

Class Base1:
       Body of the class

Class Base2:
     Body of the class

Class Derived(Base1, Base2):
     Body of the class

In the coming section, we will see the problem faced during multiple inheritance and how to tackle it with the help of examples.
 

The Diamond Problem
 

Diamond Probem

It refers to an ambiguity that arises when two classes Class2 and Class3 inherit from a superclass Class1 and class Class4 inherits from both Class2 and Class3. If there is a method “m” which is an overridden method in one of Class2 and Class3 or both then the ambiguity arises which of the method “m” Class4 should inherit.
 

When the method is overridden in both classes
 

Python3




# Python Program to depict multiple inheritance
# when method is overridden in both classes
 
class Class1:
    def m(self):
        print("In Class1")
       
class Class2(Class1):
    def m(self):
        print("In Class2")
 
class Class3(Class1):
    def m(self):
        print("In Class3") 
        
class Class4(Class2, Class3):
    pass  
     
obj = Class4()
obj.m()


Output:

In Class2

Note: When you call obj.m() (m on the instance of Class4) the output is In Class2. If Class4 is declared as Class4(Class3, Class2) then the output of obj.m() will be In Class3.
 

When the method is overridden in one of the classes
 

Python3




# Python Program to depict multiple inheritance
# when method is overridden in one of the classes
 
class Class1:
    def m(self):
        print("In Class1")
       
class Class2(Class1):
    pass
 
class Class3(Class1):
    def m(self):
        print("In Class3")   
      
class Class4(Class2, Class3):
    pass      
 
obj = Class4()
obj.m()


Output:

In Class3

When every class defines the same method

Python3




# Python Program to depict multiple inheritance
# when every class defines the same method
 
class Class1:
    def m(self):
        print("In Class1")
       
class Class2(Class1):
    def m(self):
        print("In Class2")
 
class Class3(Class1):
    def m(self):
         print("In Class3")    
     
class Class4(Class2, Class3):
    def m(self):
        print("In Class4")  
 
obj = Class4()
obj.m()
 
Class2.m(obj)
Class3.m(obj)
Class1.m(obj)


Output:

In Class4
In Class2
In Class3
In Class1

The output of the method obj.m() in the above code is In Class4. The method “m” of Class4 is executed. To execute the method “m” of the other classes it can be done using the class names.
Now, to call the method m for Class1, Class2, Class3 directly from the method “m” of the Class4 see the below example
 

Python3




# Python Program to depict multiple inheritance
# when we try to call the method m for Class1,
# Class2, Class3 from the method m of Class4
  
class Class1:
    def m(self):
        print("In Class1") 
      
class Class2(Class1):
    def m(self):
        print("In Class2")
 
class Class3(Class1):
    def m(self):
        print("In Class3")    
     
class Class4(Class2, Class3):
    def m(self):
        print("In Class4")  
        Class2.m(self)
        Class3.m(self)
        Class1.m(self)
 
obj = Class4()
obj.m()


Output:

In Class4
In Class2
In Class3
In Class1

To call “m” of Class1 from both “m” of Class2 and “m” of Class3 instead of Class4 is shown below:

Python3




# Python Program to depict multiple inheritance
# when we try to call m of Class1 from both m of
# Class2 and m of Class3
 
class Class1:
    def m(self):
        print("In Class1")  
     
class Class2(Class1):
    def m(self):
        print("In Class2")
        Class1.m(self)
 
class Class3(Class1):
    def m(self):
        print("In Class3")
        Class1.m(self)  
      
class Class4(Class2, Class3):
    def m(self):
        print("In Class4")  
        Class2.m(self)
        Class3.m(self)
      
obj = Class4()
obj.m()


Output:

In Class4
In Class2
In Class1
In Class3
In Class1

The output of the above code has one problem associated with it, the method m of Class1 is called twice. Python provides a solution to the above problem with the help of the super() function. Let’s see how it works.
 

The super Function 

Python3




# Python program to demonstrate
# super()
 
class Class1:
    def m(self):
        print("In Class1")
 
class Class2(Class1):
    def m(self):
        print("In Class2")
        super().m()
 
class Class3(Class1):
    def m(self):
        print("In Class3")
        super().m()
 
class Class4(Class2, Class3):
    def m(self):
        print("In Class4")  
        super().m()
      
obj = Class4()
obj.m()


Output:

In Class4
In Class2
In Class3
In Class1

Super() is generally used with the __init__ function when the instances are initialized. The super function comes to a conclusion, on which method to call with the help of the method resolution order (MRO).
 

Method resolution order:

In Python, every class whether built-in or user-defined is derived from the object class and all the objects are instances of the class object. Hence, the object class is the base class for all the other classes.
In the case of multiple inheritance, a given attribute is first searched in the current class if it’s not found then it’s searched in the parent classes. The parent classes are searched in a left-right fashion and each class is searched once.
If we see the above example then the order of search for the attributes will be Derived, Base1, Base2, object. The order that is followed is known as a linearization of the class Derived and this order is found out using a set of rules called Method Resolution Order (MRO).
To view the MRO of a class: 
 

  • Use the mro() method, it returns a list 
    Eg. Class4.mro()
  • Use the _mro_ attribute, it returns a tuple 
    Eg. Class4.__mro__ 
     

Example: 

Python3




# Python program to demonstrate
# super()
 
class Class1:
    def m(self):
        print("In Class1")
 
class Class2(Class1):
    def m(self):
        print("In Class2")
        super().m()
 
class Class3(Class1):
    def m(self):
        print("In Class3")
        super().m()
 
class Class4(Class2, Class3):
    def m(self):
        print("In Class4")  
        super().m()
      
print(Class4.mro())         #This will print list
print(Class4.__mro__)        #This will print tuple


Output:

[<class ‘__main__.Class4’>, <class ‘__main__.Class2’>, <class ‘__main__.Class3’>, <class ‘__main__.Class1’>, <class ‘object’>] 
(<class ‘__main__.Class4’>, <class ‘__main__.Class2’>, <class ‘__main__.Class3’>, <class ‘__main__.Class1’>, <class ‘object’>) 
 



Previous Article
Next Article

Similar Reads

How to fix Python Multiple Inheritance generates "TypeError: got multiple values for keyword argument".
Multiple inheritance in Python allows a class to inherit from more than one parent class. This feature provides flexibility but can sometimes lead to complications, such as the error: "TypeError: got multiple values for keyword argument". This error occurs when the method resolution order (MRO) leads to ambiguous function calls, especially with key
5 min read
Python Multiple Inheritance With super() Function
We are given some classes and our task is to find out how super() function works with multiple inheritance in Python. In this article, we will see how Python super() works with Multiple Inheritance. Python Multiple Inheritance With super() Below, are examples of how Python's Super() Work with Multiple Inheritance in Python: Example 1: Multiple Inhe
2 min read
OOP in Python | Set 3 (Inheritance, examples of object, issubclass and super)
We have discussed following topics on Object Oriented Programming in Python Object Oriented Programming in Python | set-1 Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing) In this article, Inheritance is introduced. One of the major advantages of Object Oriented Programming is re-use. Inheritance is one of the mechanis
4 min read
Python | super() in single inheritance
Prerequisites: Inheritance, function overriding At a fairly abstract level, super() provides the access to those methods of the super-class (parent class) which have been overridden in a sub-class (child class) that inherits from it. Consider the code example given below, here we have a class named Square and an another class named Cube which inher
6 min read
Data Classes in Python | Set 4 (Inheritance)
Prerequisites: Inheritance In Python, Data Classes in Python | Set 3 In this post, we will discuss how DataClasses behave when inherited. Though they make their own constructors, DataClasses behave pretty much the same way as normal classes do when inherited. from dataclasses import dataclass @dataclass class Article: title: str content: str author
2 min read
Types of inheritance Python
Inheritance is defined as the mechanism of inheriting the properties of the base class to the child class. Here we a going to see the types of inheritance in Python. Types of Inheritance in Python Types of Inheritance depend upon the number of child and parent classes involved. There are four types of inheritance in Python: Single Inheritance: Sing
3 min read
Inheritance in Python Inner Class
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can
3 min read
Conditional Inheritance in Python
It happens most of the time that given a condition we need to decide whether a particular class should inherit a class or not, for example given a person, if he/she is eligible for an admission in a university only then they should be a student otherwise they should not be a student. Let's consider an example, where given a condition, we want a cla
3 min read
Inheritance and Composition in Python
Prerequisite - Classes and Objects in Python This article will compare and highlight the features of is-a relation and has-a relation in Python. What is Inheritance (Is-A Relation)? It is a concept of Object-Oriented Programming. Inheritance is a mechanism that allows us to inherit all the properties from another class. The class from which the pro
4 min read
Hierarchical Inheritance with Examples in Python
In the world of object-oriented programming, inheritance is a powerful concept that allows one class to inherit the properties and behaviors of another. Hierarchical Inheritance is a specific form of inheritance in Python that involves a single base class with multiple derived classes. This article explores the concept of Hierarchical Inheritance,
4 min read
What Is Hybrid Inheritance In Python?
Inheritance is a fundamental concept in object-oriented programming (OOP) where a class can inherit attributes and methods from another class. Hybrid inheritance is a combination of more than one type of inheritance. In this article, we will learn about hybrid inheritance in Python. Hybrid Inheritance is a Type of Inheritance for know more about in
3 min read
Python | super() function with multilevel inheritance
super() function in Python: Python super function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions. It returns the proxy object that allows us to refer parent class by 'super'. To understand Python super function we must know about the inheritance. In Python inherita
3 min read
Method resolution order in Python Inheritance
Method Resolution Order : Method Resolution Order(MRO) it denotes the way a programming language resolves a method or attribute. Python supports classes inheriting from other classes. The class being inherited is called the Parent or Superclass, while the class that inherits is called the Child or Subclass. In python, method resolution order define
7 min read
Understanding the Role of Parent Class's init() in Python Inheritance
In object-oriented programming (OOP) inheritance allows classes to inherit attributes and methods from other classes. This enables code reuse and the creation of complex systems. When creating a new class (child) from an existing class (parent) a common question is whether the __init__() method of the child class should call the __init__() method o
3 min read
Inheritance in Python
One of the core concepts in object-oriented programming (OOP) languages is inheritance. It is a mechanism that allows you to create a hierarchy of classes that share a set of properties and methods by deriving a class from another class. Inheritance is the capability of one class to derive or inherit the properties from another class. Benefits of i
11 min read
Template Inheritance in Flask
Template inheritance is a very good feature of Jinja templating . Jinja is a web template engine for the Python programming language . We have seen that webpages of a website contains same footer , navigation bar etc. So instead of making same footer and navigation bar in all webpages separately , we make use of template inheritance , which allows
2 min read
Python | Iterate over multiple lists simultaneously
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over multiple lists at a time For better understanding
4 min read
Break a long line into multiple lines in Python
Break a long line into multiple lines, in Python, is very important sometime for enhancing the readability of the code. Writing a really long line in a single line makes code appear less clean and there are chances one may confuse it to be complex. Example: Breaking a long line of Python code into multiple lines Long Line: a = 1 + 2 + 3 + 4 - 5 * 2
4 min read
Python | Write multiple files data to master file
Given a number of input files in a source directory, write a Python program to read data from all the files and write it to a single master file. Source directory contains n number of files, and structure is same for all files. The objective of this code is to read all the files one by one and then append the output into a single master file having
2 min read
Python dictionary with keys having multiple inputs
Prerequisite: Python-Dictionary. How to create a dictionary where a key is formed using inputs? Let us consider an example where have an equation for three input variables, x, y, and z. We want to store values of equation for different input triplets. Example 1: C/C++ Code # Python code to demonstrate a dictionary # with multiple inputs in a key. i
4 min read
Opening multiple color windows to capture using OpenCV in Python
OpenCV is an open source computer vision library that works with many programming languages and provides a vast scope to understand the subject of computer vision.In this example we will use OpenCV to open the camera of the system and capture the video in two different colors. Approach: With the libraries available in OpenCV-Python below we will op
2 min read
Python | Check if given multiple keys exist in a dictionary
A dictionary in Python consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value. Input : dict[] = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3} keys[] = {"geeksforgeeks", "practice"} Output : Yes Input : dict[] = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3} keys[] = {"geeksforgeeks", "
3 min read
Python | Multiple Sliders widgets Controlling Background Screen or WindowColor in Kivy
Prerequisite - Slider in KivyKivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.In this article, we will learn How we can control the background color in kivy that me
3 min read
Python | Layouts in layouts (Multiple Layouts) in Kivy
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.In this article, we are going to discuss how we can use layouts in layouts basically multiple Layouts the most basi
5 min read
Multiple Exception Handling in Python
Given a piece of code that can throw any of several different exceptions, and one needs to account for all of the potential exceptions that could be raised without creating duplicate code or long, meandering code passages. If you can handle different exceptions all using a single block of code, they can be grouped together in a tuple as shown in th
3 min read
Python | How to use Multiple kv files in kivy
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. In this article, we will see how can we use multiple .kv files in a single Application . This is the Python progra
3 min read
Save multiple matplotlib figures in single PDF file using Python
In this article, we will discuss how to save multiple matplotlib figures in a single PDF file using Python. We can use the PdfPages class's savefig() method to save multiple plots in a single pdf. Matplotlib plots can simply be saved as PDF files with the .pdf extension. This saves Matplotlib-generated figures in a single PDF file named Save multip
3 min read
How to use multiple UX Widgets in kivy | Python
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. ???????? Kivy Tutorial - Learn Kivy with Examples. UX Widgets: Classical user interface widgets, ready to be assem
3 min read
Python | Replacing Nth occurrence of multiple characters in a String with the given character
Given a String S, a character array ch[], a number N and a replacing character, the task is to replace every Nth occurrence of each character of the character array ch[] in the string with the given replacing character. Input: S = "GeeksforGeeks", ch[] = {'G', 'e', 'k'}, N = 2, replacing_character = '#' Output: Ge#ksfor#ee#s Explanation: In the giv
4 min read
Python - Create multiple toolbars in wxPython
As we created a single toolbar in our previous article we are now going to learn how can we create multiple toolbars in wxPython. So we are going to create two toolbars and add tools to both of them. Steps :1. Create a vertical sizer. 2. Create first toolbar. 3. Add tools to first toolbar. 2. Create second toolbar. 3. Add tools to second toolbar. 4
1 min read
Practice Tags :
three90RightbarBannerImg