The Wayback Machine - https://web.archive.org/web/20240828061415/https://www.geeksforgeeks.org/method-resolution-order-in-python-inheritance/
Open In App

Method resolution order in Python Inheritance

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 defines the order in which the base classes are searched when executing a method. First, the method or attribute is searched within a class and then it follows the order we specified while inheriting. This order is also called Linearization of a class and set of rules are called MRO(Method Resolution Order). While inheriting from another class, the interpreter needs a way to resolve the methods that are being called via an instance. Thus we need the method resolution order. For Example 
 

Python
# Python program showing
# how MRO works

class A:
    def rk(self):
        print(" In class A")
class B(A):
    def rk(self):
        print(" In class B")

r = B()
r.rk()

Output: 
 

 In class B


In the above example the methods that are invoked is from class B but not from class A, and this is due to Method Resolution Order(MRO). 
The order that follows in the above code is- class B – > class A 
In multiple inheritances, the methods are executed based on the order specified while inheriting the classes. For the languages that support single inheritance, method resolution order is not interesting, but the languages that support multiple inheritance method resolution order plays a very crucial role. Let’s look over another example to deeply understand the method resolution order: 
 

Python
# Python program showing
# how MRO works

class A:
    def rk(self):
        print(" In class A")
class B(A):
    def rk(self):
        print(" In class B")
class C(A):
    def rk(self):
        print("In class C")

# classes ordering
class D(B, C):
    pass
   
r = D()
r.rk()

Output: 
 

 In class B


In the above example we use multiple inheritances and it is also called Diamond inheritance and it looks as follows: 
 


Python follows a depth-first lookup order and hence ends up calling the method from class A. By following the method resolution order, the lookup order as follows. 
Class D -> Class B -> Class C -> Class A 
Python follows depth-first order to resolve the methods and attributes. So in the above example, it executes the method in class B. 
  
Old and New Style Order : 
In the older version of Python(2.1) we are bound to use old-style classes but in Python(3.x & 2.2) we are bound to use only new classes. New style classes are the ones whose first parent inherits from Python root ‘object’ class. 
 

Python
# Old style class
class OldStyleClass: 
    pass

# New style class
class NewStyleClass(object): 
    pass

Method resolution order(MRO) in both the declaration style is different. Old style classes use DLR or depth-first left to right algorithm whereas new style classes use C3 Linearization algorithm for method resolution while doing multiple inheritances. 
  
DLR Algorithm 
During implementing multiple inheritances, Python builds a list of classes to search as it needs to resolve which method has to be called when one is invoked by an instance. As the name suggests, the method resolution order will search the depth-first, then go left to right. For Example 
 

Python
class A: 
    pass


class B: 
    pass


class C(A, B): 
    pass


class D(B, A): 
    pass


class E(C,D): 
    pass

In the above Example algorithm first looks into the instance class for the invoked method. If not present, then it looks into the first parent, if that too is not present then-parent of the parent is looked into. This continues till the end of the depth of class and finally, till the end of inherited classes. So, the resolution order in our last example will be D, B, A, C, A. But, A cannot be twice present thus, the order will be D, B, A, C. But this algorithm varying in different ways and showing different behaviours at different times .So Samuele Pedroni first discovered an inconsistency and introduce C3 Linearization algorithm. 
  
C3 Linearization Algorithm : 
C3 Linearization algorithm is an algorithm that uses new-style classes. It is used to remove an inconsistency created by DLR Algorithm. It has certain limitation they are: 
 

  • Children precede their parents
  • If a class inherits from multiple classes, they are kept in the order specified in the tuple of the base class.


C3 Linearization Algorithm works on three rules: 
 

  • Inheritance graph determines the structure of method resolution order.
  • User have to visit the super class only after the method of the local classes are visited.
  • Monotonicity


  
Methods for Method Resolution Order(MRO) of a class: 
To get the method resolution order of a class we can use either __mro__ attribute or mro() method. By using these methods we can display the order in which methods are resolved. For Example 
 

Python
# Python program to show the order
# in which methods are resolved

class A:
    def rk(self):
        print(" In class A")
class B:
    def rk(self):
        print(" In class B")

# classes ordering
class C(A, B):
    def __init__(self):
        print("Constructor C")

r = C()

# it prints the lookup order 
print(C.__mro__)
print(C.mro())

Output: 
 

Constructor C

(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)

[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]


Method resolution order in Python Inheritance – FAQs

What is the order of class inheritance in Python?

The order of class inheritance in Python follows the Method Resolution Order (MRO). MRO determines the order in which base classes are searched when executing a method. It is determined using the C3 linearization algorithm, also known as C3 superclass linearization. You can view the MRO of a class using the __mro__ attribute or the mro() method. 

How in what order are methods resolved during multiple inheritance?

In Python, methods are resolved using the MRO, which is determined by the C3 linearization algorithm. This algorithm ensures that a consistent order is maintained, prioritizing the leftmost base class first and then following the order of inheritance.

Example:

class A:
def method(self):
print("A")

class B(A):
def method(self):
print("B")

class C(A):
def method(self):
print("C")

class D(B, C):
pass

d = D()
d.method() # Output: B
print(D.__mro__) # Output: (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

How to fix TypeError: cannot create a consistent method resolution order in MRO in Python?

This error occurs when the inheritance hierarchy is ambiguous and cannot produce a consistent MRO. To fix this, you need to rearrange the inheritance order to make it consistent.

Example:

class X:
pass

class Y(X):
pass

class Z(X):
pass

class A(Y, Z): # This will raise TypeError
pass

# Fix by rearranging the inheritance
class A(Z, Y):
pass

How does Python resolve multiple inheritances?

Python resolves multiple inheritances using the C3 linearization algorithm to determine the MRO. This algorithm ensures that the inheritance order is consistent and that each class appears before its parents.

What is the MRO diamond problem in Python?

The MRO diamond problem occurs when a class inherits from two classes that both inherit from a common superclass, forming a diamond-shaped inheritance diagram. This can cause ambiguity in method resolution. Python’s C3 linearization algorithm resolves this by ensuring that each class appears in the MRO after its parents, maintaining a consistent and unambiguous order.

Example:

class A:
def method(self):
print("A")

class B(A):
def method(self):
print("B")

class C(A):
def method(self):
print("C")

class D(B, C):
pass

d = D()
d.method() # Output: B
print(D.__mro__) # Output: (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

In this example, class D inherits from both B and C, which both inherit from A. The MRO ensures that B is checked before C due to the inheritance order in D(B, C)



Similar Reads

How To Fix "Typeerror: Cannot Create A Consistent Method Resolution Order (Mro)" In Python
When working with Python, it is usual to encounter mistakes. One such issue, "TypeError: Cannot create a consistent method resolution order (MRO)," might be very aggravating. This issue usually occurs when there is a dispute in the inheritance structure of classes. In this article, we will explore the causes of this error and provide effective solu
3 min read
Scope Resolution in Python | LEGB Rule
Here, we will discuss different concepts such as namespace, scope, and LEGB rule in Python. What are Namespaces in Python A python namespace is a container where names are mapped to objects, they are used to avoid confusion in cases where the same names exist in different namespaces. They are created by modules, functions, classes, etc. What is Sco
5 min read
Python | Pandas TimedeltaIndex.resolution
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.resolution attribute return a string representing the lowest resolution that we have for the given TimedeltaIndex
2 min read
Finding the Size Resolution of Image in Python
Let us see how to find the resolution of an image in Python. We will be solving this problem with two different libraries which are present in Python: PILOpenCV In our examples we will be using the following image: The resolution of the above image is 600x135. Using PIL We will be using a library named Pillow to find the size(resolution) of the ima
2 min read
Change image resolution using Pillow in Python
Prerequisites: Python pillow PIL is the Python Imaging Library which provides the python interpreter with an in-depth file format support, an efficient internal representation, and fairly powerful image processing capabilities. Changing the resolution of an image simply means reducing or increasing the number of pixels in an image, without changing
2 min read
“CAP_IMAGES: Can't Find Starting Number” Error in Python with Resolution
The error "CAP_IMAGES: Can't Find Starting Number" typically occurs in the context of the OpenCV when attempting to open a video file or capture device. This error message indicates that OpenCV encountered difficulties in reading or parsing the video stream due to the missing or incorrect starting frame number. Why “CAP_IMAGES: Can't Find Starting
5 min read
PyQt5 QCalendarWidget - Getting Horizontal Resolution
In this article we will see how we can get the horizontal resolution of the QCalendarWidget. In order to do this we use logicalDpiX method, it returns the horizontal resolution of the device in dots per inch, which is used when computing font sizes. For X11, this is usually the same as could be computed from widthMM(). In order to do this we will u
2 min read
PyQt5 QCalendarWidget - Getting Vertical Resolution
In this article we will see how we can get the vertical resolution of the QCalendarWidget. In order to do this we use logicalDpiY method, it returns the vertical resolution of the device in dots per inch, which is used when computing font sizes. For X11, this is usually the same as could be computed from heightMM(). In order to do this we will use
2 min read
Pafy - Getting Resolution of Stream
In this article we will see how we can get the resolution of the given youtube video stream in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Resolution is the quality of the video stream, the most popular standard resolutions are
2 min read
Dependency resolution and lock files In Pyhton Poetry
Lock files are a fundamental component of dependency management in modern software development. They serve as a snapshot of the exact versions of all dependencies that an application relies on at a given point in time. In the context of Python Poetry, the poetry.lock file is automatically generated and updated whenever dependencies are added, remov
4 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
Multiple Inheritance in Python
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 ca
5 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 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
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
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
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
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Python MySQL - Order By Clause
A connector is employed when we have to use MySQL with other programming languages. The work of MySQL-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. OrderBy Clause OrderBy is used to arrange the result set in either ascending or descendi
2 min read
Python | Check order of character in string using OrderedDict( )
Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there won’t be any duplicate characters in the pattern. Examples: Input: string = "engineers rock"pattern = "er";Output: trueExplanation: All 'e' in the input string are before all 'r'.Input:
3 min read
Python code to print common characters of two Strings in alphabetical order
Given two strings, print all the common characters in lexicographical order. If there are no common letters, print -1. All letters are lower case. Examples: Input : string1 : geeks string2 : forgeeks Output : eegks Explanation: The letters that are common between the two strings are e(2 times), g(1 time), k(1 time) and s(1 time). Hence the lexicogr
2 min read