Skip to content

Instantly share code, notes, and snippets.

@dutc
Created August 31, 2021 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dutc/5358862a1905db3948c46d45f35ee75d to your computer and use it in GitHub Desktop.
Save dutc/5358862a1905db3948c46d45f35ee75d to your computer and use it in GitHub Desktop.
“Python Expert” Newsletter (Sep 8, 2021): Learning Corner
class A:
def foo(self):
return 'A.foo',
class B(A):
def foo(self):
return 'B.foo', *super().foo()
class C(A):
def foo(self):
return 'C.foo', *super().foo()
class D(B, C):
def foo(self):
return 'D.foo', *super().foo()
if __name__ == '__main__':
print(
f'{A.__mro__ = }',
f'{A().foo() = }',
f'{B.__mro__ = }',
f'{B().foo() = }',
f'{C.__mro__ = }',
f'{C().foo() = }',
f'{D.__mro__ = }',
f'{D().foo() = }',
sep='\n'
)
@dutc
Copy link
Author

dutc commented Aug 31, 2021

As you can see:

  • Python 2's “new-style classes” introduced the “method resolution order”—a linearised ordering of base classes
  • this “MRO" (accessible via __mro__) determines the order in which super() will operate
  • super() is one of the few cases where “what you see is not what you get” in Python (another is class-attribute name-mangling)

@dutc
Copy link
Author

dutc commented Aug 31, 2021

For the full write-up and discussion, sign up for the “Python Expert” newsletter!

bit.ly/expert-python

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