Skip to content

Instantly share code, notes, and snippets.

@webknjaz
Created November 17, 2020 17:19
Show Gist options
  • Save webknjaz/a0d606f511c3fa452dd0c44da2585fd4 to your computer and use it in GitHub Desktop.
Save webknjaz/a0d606f511c3fa452dd0c44da2585fd4 to your computer and use it in GitHub Desktop.
This snippet showcases how to decorate methods declared in child classes
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