Method resolution order in Python inheritance

| | | | | | | | | | | | | | |

# Show Python program
# how MRO works

 

class A:

def rk ( self ):

print ( "In class A" )

class B (A):

def rk ( self ):

prin t ( "In class B" )

 

r = B ()

r.rk ()

Exit:

 In class B 

In the above example, methods are called from class B but not from class A, and this is due to the Method Resolution Order (MRO). 
The order that follows in the above code is —  class B - & gt; class A
With multiple inheritance, methods are executed in the order specified when classes are inherited. For languages ​​that support single inheritance, the order of resolution of methods is not interesting, but languages ​​that support the order of resolution of multiple inheritance methods are very important. Let`s look at another example to get a deeper understanding of the method resolution order:

# Show Python program
# 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 " )

  
# ordering classes

class D (B, C):

pass

 

r = D ()

r.rk ()

Output:

 In class B 

In the above example, we use multiple inheritance, and it is also called Diamond inheritance or Deadly Diamond of Death and looks like this:

Python follows the depth-first search order and therefore ends up calling a method from class A. Following the method resolution order, the search order looks like this way. 
Class D - & gt; Class B - & gt; Class C - & gt; Class A
Python follows first order depth for resolving methods and attributes. So in the above example, it executes the method in class B.

Old and new style of ordering:
In the older version of Python (2.1), we are required to use the classes old style, but in Python (3.x and 2.2) we are required to use only new classes. The new style classes are those whose first parent class inherits from the root Python object class.

# Old style class

class OldStyleClass: 

pass

 
# New style class

class NewStyleClass ( object ): 

pass

Method Resolution Order (MRO) is different in both declaration styles. The old style classes use the DLR algorithm or left to right left to right, while the new style classes use the C3 linearization algorithm to resolve the method across multiple inheritance.

DLR Algorithm
While implementing multiple inheritances, Python creates a list of classes to look for because it needs to determine which method should be called when the instance is called. As the name suggests, the order of resolving the method will first look for depth and then go from left to right. For example

class A: 

  pass

  

 

class B: 

pass

 

 

class C (A, B): 

pass

 

 

class D (B, A): 

pas s

 

 

class E (C, D): 

pass

In the above Example, the algorithm first looks at the instance class for the called method. If it is not there, then it looks at the first parent, if it is also not there, then the parent-parent is considered. This continues to the end of the class depth and finally to the end of the inherited classes. So the order of resolution in our last example will be D, B, A, C, A. But, A cannot be represented twice, so the order will be D, B, A, C. But this algorithm changes in different ways and demonstrating different behavior at different times. So Samuele Pedroni first discovered the inconsistency and presented the C3 linearization algorithm.

C3 linearization algorithm:
C3 linearization algorithm — it is an algorithm using new style classes. It is used to resolve the inconsistency created by the DLR algorithm. It has certain restrictions:

  • Children precede their parents
  • If a class inherits from multiple classes, they are stored in the order specified in the base class tuple.
  • The C3 linearization algorithm works according to three rules:

    • The inheritance graph defines the structure of how methods are resolved.
    • The user should only visit the superclass after visiting a local class method.
    • Monotony

    Methods for the method resolution order (MRO) of a class:
    To get the resolution order of a class method we can use the mro () or mro () attribute. Using these methods, we can display the order in which the methods are allowed. For example

    # Python program for showing order
    # in which methods are allowed

     

    class A:

    def rk ( self ):

    print ( "In class A" )

    class B:

      def rk ( self ):

    print ( "In class B" )

     
    # ordering classes

    class C (A, B):

      def __ init __ ( self ):

    print ( " Constructor C " )

      

    r = C ( )

     
    # prints the search order

    print (C .__ mro __)

    print (C.mro ())

    Exit :

     C constructor (& lt; class & # 39; __ main __. C & # 39; & gt ;, & lt; class & # 39; __ main __. A & # 39; & gt ;, & lt; class & # 39; __ main __. B & # 39; & gt ;, & lt; class & # 39; object & # 39; & gt;) [& lt; class & # 39; __ main __. C & # 39; & gt ;, & lt; class & # 39; __ main __. A & # 39; & gt ;, & lt; class & # 39; __ main __. B & # 39; & gt ;, & lt; class & # 39; object & # 39; & gt;] 

Shop

Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$
Gifts for programmers

Best laptop for Zoom

$499
Gifts for programmers

Best laptop for Minecraft

$590

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically