Created
November 17, 2020 17:19
-
-
Save webknjaz/a0d606f511c3fa452dd0c44da2585fd4 to your computer and use it in GitHub Desktop.
This snippet showcases how to decorate methods declared in child classes
This file contains hidden or 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
from contextlib import contextmanager | |
@contextmanager | |
def show_start_end(): | |
print('START') | |
try: | |
yield | |
finally: | |
print('THE END') | |
def decorate(function): | |
def wrapper(*args, **kwargs): | |
with show_start_end(): | |
return function(*args, **kwargs) | |
return wrapper | |
class Parent: | |
def __init_subclass__(cls): | |
print('INIT') | |
print(cls.some_method) | |
super().__init_subclass__() | |
print(cls.some_method) | |
cls.some_method = decorate(cls.some_method) | |
print(cls.some_method) | |
class Child(Parent): | |
def some_method(self): | |
return 'some' | |
print(Child().some_method()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment