The diamond problem

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.

Overriding and super:—

This is what the super function does; it returns the object as an instance of the parent class, allowing us to call the parent method directly:

The diamond problem:

we have a base class that has a method named call_me. Two subclasses override that method, and then another subclass extends both of these using multiple inheritance. This is called diamond inheritance because of the diamond shape of the class diagram:

Diamonds are what makes multiple inheritance tricky. Technically, all multiple inheritance in Python 3 is diamond inheritance, because all classes inherit from object.

This example simply ensures each overridden call_me method directly calls the parent method with the same name. Each time it is called, it lets us know by printing the information to the screen, and updates a static variable on the class to show how many times it has been called. If we instantiate one Subclass object and call the method on it once, we get this

The base class’s call_me method has been called twice. This isn’t expected behavior and can lead to some very difficult bugs if that method is doing actual work—like depositing into a bank account twice.

our base method is only being called once. super() actually doing here Since the print statements are executed after the super calls, the printed output is in the order each method is actually executed.

First call_me of Subclass calls super().call_me(), which happens to refer to LeftSubclass.call_me(). LeftSubclass.call_me() then calls super().call_ me(), but in this case, super() is referring to RightSubclass.call_me(). Pay particular attention to this; the super call is not calling the method on the superclass of LeftSubclass (which is BaseClass), it is calling RightSubclass, even though it is not a parent of LeftSubclass! This is the next method, not the parent method. RightSubclass then calls BaseClass and the super calls have ensured each method in the class hierarchy is executed once.

Open chat