https://realpython.com/blog/python/primer-on-python-decorators/
def decorator1(my_func):
def warpper(*args, **kwargs):
print("before my_func!!!")
my_func(*args, **kwargs)
print("after my_func!!!")
return warpper
from functools import wraps
def decorator2(my_func):
@wraps(my_func)
def warpper(*args, **kwargs):
print("before my_func!!!")
my_func(*args, **kwargs)
print("after my_func!!!")
return warpper
@decorator1
def my_func1(a, b):
print(a + b)
@decorator2
def my_func2(a, b):
print(a + b)
print(my_func1.__name__)
# out: warpper
print(my_func2.__name__)
# out: my_func2
from functools import wraps
def dec(*a, **kw):
def decorator(my_func):
@wraps(my_func)
def warpper(*args, **kwargs):
print(*a)
print(**kw)
for i in range(kw[n]):
print("wrapper!!")
#print(**kwargs)
my_func(*args, **kwargs)
return warpper
return decorator
@dec(1,2,3, n=4, m=5)
def my_func(a, b):
print(a + b)
my_func(1,2)
# output:
# (1, 2, 3)
# {'m': 5, 'n': 4}
# wrapper!!
# 3
# wrapper!!
# 3
# wrapper!!
# 3
# wrapper!!
# 3
# more examples https://krzysztofzuraw.com/blog/2016/python-class-decorators.html
class decorator(object):
def __init__(self, func):
self.func = func
def __call__(self, *args):
print('Called {func} with args: {args}'.format(func=self.func.func_name,
args=args))
return self.func(*args)
@decorator
def func(x,y):
return x,y
if __name__ == '__main__':
func(1,2)