Python中函数装饰器是一种修改其他函数功能的函数,只需要在被装饰的函数前加上@<装饰器名> 就可以为该函数增加装饰器。下面代码就是定义并调用一个经典的装饰器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import functools def decorator_example(view_func): @functools.wraps(view_func) def decorator_func(*args, **kwargs): print('this is decorator') return view_func(*args, **kwargs) return decorator_func @decorator_example def func(): print('This is a function') if __name__ == '__main__': func() |
输出为:
1 2 3 4 |
this is decorator This is a function 进程已结束,退出代码0 |
而如果我们的装饰器在执行过程中产生了某些变量,而我们希望将这些变量传入到被装饰的函数中时,我们可以这样操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import functools def decorator_example(view_func): @functools.wraps(view_func) def decorator_func(*args, **kwargs): a_str='This is a string from the decorator' args_list=list(args) args_list.append(a_str) return view_func(*args_list, **kwargs) return decorator_func @decorator_example def func(str): print(str) if __name__ == '__main__': func() |
输出结果为:
1 2 3 |
This is a string from the decorator 进程已结束,退出代码0 |
由于args是元组类型,无法直接修改,所以我们需要先转换为list类型,然后把我们想要传递的变量追加到args后面,这样就可以实现将装饰器的变量传到函数的效果了。