5

Out of pure curiosity I did the following.

class A:
    def x():
        print("A.x")

class B:
    def x():
        print("B.x")

class C(A,B):
    pass

C.x()

Which outputs

A.x

Now the behavior I expected was the later superclass's method B.x executing. Because I thought that methods for A will be defined first than methods of B will override them. Instead, A.x was printed. In fact the first superclass's method .x was always called. The same behavior was shown with instance methods.

Can anyone explain the way this is happening please?

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
Inyoung Kim 김인영
  • 1,434
  • 1
  • 17
  • 38
  • 6
    It's called method resolution order. Google for `class.__mro__`. Basically the order of resolution is in the class attribute `__mro__` (So, `A.__mro__` and so on) – Niloct Nov 23 '20 at 13:20
  • 4
    Try `print(C.__mro__)` to print the method resolution order. – Klaus D. Nov 23 '20 at 13:20
  • On a side note, you want `@classmethod` decorating those methods. – Daniel Walker Nov 24 '20 at 02:34
  • 1
    And while figuring out the MRO of a class heirarchy with multiple inheritance is non-trivial, for a definition like: `class C(A,B)` in the MRO, it will always be `[C, A, B, ..., object]` – juanpa.arrivillaga Nov 24 '20 at 02:49

0 Answers0