Last active
March 24, 2020 19:41
-
-
Save mattroseman/674a89d5da1fa3bdb07338983087fcb1 to your computer and use it in GitHub Desktop.
Example implementations of how Python's super() function works
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should output