Search code examples
pythonmethod-resolution-order

Does order of class bases in python matter?


Is there a (meaningful) difference the two classes below?

class A(Foo, Bar):
    ...

vs

class B(Bar, Foo):
    ...

Solution

  • Does order of class bases in python matter?

    Yes, it does. Consider the following:

    class A:
        def foo(self):
            print('class A')
    class B:
        def foo(self):
            print('class B')
    class C(A, B):
        pass
    
    c = C()
    c.foo() # class A
    

    Methods are resolved from left-to-right—e.g., in the example, the foo method comes from class A because A comes before B.