Skip to content

Instantly share code, notes, and snippets.

@Sean-Bradley
Last active March 3, 2019 20:57
Show Gist options
  • Save Sean-Bradley/d6cee6435c56b7ddfd0e9c65eaa7713f to your computer and use it in GitHub Desktop.
Save Sean-Bradley/d6cee6435c56b7ddfd0e9c65eaa7713f to your computer and use it in GitHub Desktop.
Testing Python Inheritance Override Order
class Foo:
def testOverideOrder(self):
print("Foo")
class Bar:
def testOverideOrder(self):
print("Bar")
class TestFooBar(Foo, Bar):
pass
class TestBarFoo(Bar, Foo):
pass
testFooBar = TestFooBar()
testBarFoo = TestBarFoo()
testFooBar.testOverideOrder()
testBarFoo.testOverideOrder()
@Sean-Bradley
Copy link
Author

Sean-Bradley commented Mar 1, 2019

output from script

$ python myscript.py
Foo
Bar

By running the attached function you'll see that the order of inheritance in a python class declaration matters.
The 1st inherited class method overrides any identical method signatures in any further inherited classes .
The order of precedence is left to right.

So, in case of calling the testFooBar.testOverideOrder() method, the inherited Foo's testOverideOrder method is called,
and in case of calling the testBarFoo.testOverideOrder() method, the inherited Bar's testOverideOrder method is called.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment