Class based decorators - AndrewMZ6/python_cheat_sheet GitHub Wiki
Using classes instead of functions to create decorator
class decoratorClass:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print('additional functionality')
self.func(*args, **kwargs)
@decoratorClass # equivalent to -> myfunc = decoratorClass(myfunc)
def myfunc(x): # this means that myfunc becomes an instance of
print(f"x: {x}") # decoratorClass class
myfunc(10) # and then the instance gets "__call__"ed
# OUTPUT
# additional functionality
# x: 10
And parametrized decorator of course!
class decoratorClass:
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, func):
def wrapper(*args, **kwargs):
print(f'additional functionality using {self.args, self.kwargs}')
func(*args, **kwargs)
return wrapper
@decoratorClass('some', 3.14, "parameters here") # equivalent to -> myfunc = decoratorClass(*args, **kwargs)(myfunc)
def myfunc(x): # first we create an instance of the decoratorClass with some parameters.
print(f"x: {x}") # then we "__call__" the instance, passing it func as an argument
myfunc(10)
# OUTPUT
# additional functionality using (('some', 3.14, 'parameters here'), {})
# x: 10