Multiple Inheritance in Python
Last Updated :
22 Feb, 2022
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.
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
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'>)
Similar Reads
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Classes and Objects A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type.Classes are created using class ke
6 min read
Python objects 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
2 min read
Class and Object
self in Python classIn Python, self is a fundamental concept when working with object-oriented programming (OOP). It represents the instance of the class being used. Whenever we create an object from a class, self refers to the current object instance. It is essential for accessing attributes and methods within the cla
6 min read
Class and Instance Attributes in PythonClass attributes: Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. Python # Write Python code here class sampleclass: count = 0 # class attribute def increase(self): samplecla
2 min read
Create a Python SubclassIn Python, a subclass is a class that inherits attributes and methods from another class, known as the superclass or parent class. When you create a subclass, it can reuse and extend the functionality of the superclass. This allows you to create specialized versions of existing classes without havin
3 min read
Inner Class in PythonPython is an Object-Oriented Programming Language, everything in Python is related to objects, methods, and properties. A class is a user-defined blueprint or a prototype, which we can use to create the objects of a class. The class is defined by using the class keyword.Example of classPython# creat
5 min read
Python MetaClassesThe key concept of python is objects. Almost everything in python is an object, which includes functions and as well as classes. As a result, functions and classes can be passed as arguments, can exist as an instance, and so on. Above all, the concept of objects let the classes in generating other c
9 min read
Creating Instance Objects in PythonIn Python, an instance object is an individual object created from a class, which serves as a blueprint defining the attributes (data) and methods (functions) for the object. When we create an object from a class, it is referred to as an instance. Each instance has its own unique data but shares the
3 min read
Dynamic Attributes in PythonDynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for
2 min read
Constructors in PythonIn Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
3 min read
Why Python Uses 'Self' as Default ArgumentIn Python, when defining methods within a class, the first parameter is always self. The parameter self is a convention not a keyword and it plays a key role in Pythonâs object-oriented structure.Example:Pythonclass Car: def __init__(self, brand, model): self.brand = brand # Set instance attribute s
3 min read
Encapsulation and Access Modifiers
Encapsulation in PythonIn Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage.Table of ContentEnca
6 min read
Access Modifiers in Python : Public, Private and ProtectedPrerequisites: Underscore (_) in Python, Private Variables in PythonEncapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be chan
9 min read
Access Modifiers in Python : Public, Private and ProtectedPrerequisites: Underscore (_) in Python, Private Variables in PythonEncapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be chan
9 min read
Private Variables in PythonPrerequisite: Underscore in PythonIn Python, there is no existence of âPrivateâ instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
3 min read
Private Methods in PythonEncapsulation is one of the fundamental concepts in object-oriented programming (OOP) in Python. It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of
6 min read
Protected variable in PythonPrerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a cl
2 min read
Inheritance
Inheritance in PythonInheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
7 min read
Method Overriding in PythonMethod overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameter
7 min read
Operator Overloading in PythonOperator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed t
8 min read
Python super()In Python, the super() function is used to refer to the parent class or superclass. It allows you to call methods defined in the superclass from the subclass, enabling you to extend and customize the functionality inherited from the parent class.Syntax of super() in PythonSyntax: super()Return : Ret
8 min read
Multiple Inheritance in PythonInheritance 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
5 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 Inheritan
3 min read
Multilevel Inheritance in PythonPython is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Multilevel Inheritance in PythonPython is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Polymorphism
Abstraction
Special Methods and Testing
Additional Resources