Skip to content

Instantly share code, notes, and snippets.

@mattroseman
Last active March 24, 2020 19:41
Show Gist options
  • Save mattroseman/674a89d5da1fa3bdb07338983087fcb1 to your computer and use it in GitHub Desktop.
Save mattroseman/674a89d5da1fa3bdb07338983087fcb1 to your computer and use it in GitHub Desktop.
Example implementations of how Python's super() function works
class A:
def foo(self):
print('A foo method')
def bar(self):
print('A bar method')
class B(A):
def foo(self):
print('B foo method')
def bar(self):
print('B bar method')
super().bar()
class C(B):
def foo(self):
print('C foo method')
def bar(self):
print('C bar method')
super().bar() # this is the same as calling `super(C, self).bar()`
def main():
c = C()
print('calling inherited methods outside of the class')
# First argument is the class to elevate from to find implementation of foo method.
# So by passing in C you are saying, look at the parent classes of C for an implementation of foo.
# Second argument is an object the method will be called on.
super(C, c).foo()
super(B, c).foo()
print('calling super without arguments outside of a class won\'t work')
try:
super().foo()
except RuntimeError as err:
print(f'`super().foo()` throws Runtime Error {err}')
print('\n')
print('calling inherited methods inside of the class')
c.bar()
if __name__ == '__main__':
main()
@mattroseman
Copy link
Author

Should output

calling inherited methods outside of the class
B foo method
A foo method
calling super without arguments outside of a class won't work
`super().foo()` throws Runtime Error super(): no arguments


calling inherited methods inside of the class
C bar method
B bar method
A bar method

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