ruk·si

🐍 Python
Method Resolution Order

Updated at 2017-01-03 01:22

Understand method resolution order. Undefined variables and methods are searched from base class.

class A:
    x: int = 1

class B(A):
    pass

class C(A):
    pass

assert (A.x, B.x, C.x) == (1, 1, 1)

B.x = 2
assert (A.x, B.x, C.x) == (1, 2, 1)

A.x = 3
assert (A.x, B.x, C.x) == (3, 2, 3)

Method resolution order defines search order for instance method calls. Subclass declaration defines which classes are searched first.

class A:
    def ping(self) -> None:
        print(f'ping: A')

class B(A):
    def pong(self) -> None:
        print(f'pong: B')

class C(A):
    def pong(self) -> None:
        print(f'pong: C')

class D(B, C):
    def ping(self) -> None:
        print(f'ping: D')

    def pingpong(self) -> None:
        self.ping()     # ping: D
        super().ping()  # ping: A
        self.pong()     # pong: B
        super().pong()  # pong: B
        C.pong(self)    # pong: C

# Method resolution order shows in which order the methods are searched.
assert D.__mro__ == (D, B, C, A, object)

d = D()
d.pingpong()
# ping: D
# ping: A
# pong: B
# pong: B
# pong: C
  • Fluent Python, Luciano Ramalho