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 wrapper
return 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’)