Python Advanced (9) – MRO (Method Resolution Order)

◎Knowledge points

  1. Definition and Examples of MRO

◎Script practice

 """MRO"""  """ The full name of MRO is Method Resolution Order, which refers to the order in which the python interpreter searches for methods on the class inheritance tree when the method of the instance object corresponding to the lowest class object is called for a class inheritance tree. For a class inheritance tree, you can call the method mro() of the lowest class object or access the special attribute __mro__ of the lowest class object, Get the MRO of this class inheritance tree """  class A(object): def f(self): print("Af")  class B(A): def f(self): print("Bf")  class C(A): def f(self): print("Cf")  class D(B, C): def f(self): print("Df")  # [<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>] print(D.mro())  # (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>) print(D.__mro__)  d = D() df() # Df  """ When the overridden method in the parent class is called through super() in the overridden method of the subclass, the order of searching methods in the parent class is based on the MRO of the class inheritance tree with the subclass as the lowest class object If you want to call the overridden method in the specified parent class, you can pass two arguments to super(): super(a_type, obj), where, The first argument a_type is a class object, and the second argument obj is an instance object, so that the specified superclass is: In the MRO of the class object corresponding to obj, the class object """ after a_type  class A(object): def f(self): print("Af")  class B(A): def f(self): print("Bf")  class C(A): def f(self): print("Cf")  class D(B, C): def f(self): super().f() # Bf # super(D, self).f() # Bf # super(B, self).f() # Cf # super(C, self).f() # Af  d = D() df() # Bf 

MRO.png

◎Script address: https://github.com/anzhihe/learning/blob/master/python/practise/learn-python/python_advanced/mro.py

This article is reprinted from: https://chegva.com/5218.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment