• How to use Method Resolution Order (MRO) in new-style classes in python?

    How to use Method Resolution Order (MRO) in new-style classes in python?

     

    Silver Member Asked on June 1, 2018 in Python.
    Add Comment
  • 2 Answer(s)
    Best answer

    The Python Method Resolution Order defines the class search path used by Python to search for the right method to use in classes having multi-inheritance.The algorithm change is also refereed as old classes and new classes MRO algorithm. The new one is not so easy to bring out.

     

    class A:
    
    def methodA(self):
    
    print("I am a A")
    class B(A):
    
    def methodA(self):
    
    print("I am a B")
    class C(A):
    
    def methodA(self):
    
    print("I am a C")
    class D(B,C):
    
    def methodA(self):
    
    print("I am a D")
    d1 = D()
    
    d1.methodA()
    

     

    Silver Member Answered on June 1, 2018.
    Add Comment

     

    class X: pass
    
    class Y: pass
    
    class Z: pass
    class A(X,Y): pass
    
    class B(Y,Z): pass
    class M(B,A,Z): pass
    # Output:
    
    # [<class '__main__.M'>, <class '__main__.B'>,
    
    # <class '__main__.A'>, <class '__main__.X'>,
    
    # <class '__main__.Y'>, <class '__main__.Z'>,
    
    # <class 'object'>]
    print(M.mro())
    

     

    Silver Member Answered on June 1, 2018.
    Add Comment
  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.