本文主要是介绍【python】——自定义参数装饰器的例子与解释,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
code
def repeat(num):def my_decorator(func):def wrapper(*args, **kwargs):for i in range(num):print('wrapper of decorator {}'.format(i))func(*args, **kwargs)return wrapperreturn my_decorator@repeat(4)
def greet(message):print(message)greet('hello world')# 输出:
# wrapper of decorator 0
# hello world
# wrapper of decorator 1
# hello world
# wrapper of decorator 2
# hello world
# wrapper of decorator 3
# hello world
这里装饰器@repeat(4)的整个流程为:
- 首先执行repeat(4)函数,返回my_decorator,num=4在repeat函数域都可用
- 于是@repeat(4)变成了@my_decorator,这就变成了普通的装饰器
- @my_decorator等价于 greet = wrapper
- 执行greet(‘hello world’) 等价于执行 wrapper(‘hello world’)
这篇关于【python】——自定义参数装饰器的例子与解释的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!