一个函数添加多个装饰器
在函数声明的上方每一行添加一个装饰器, 这个多个装饰器就像一条链一样.
on = True
def strong1(fun): # fun 将来就是被替换的 hello
global on
if on:
def new_hello():
print("我是装饰器1中的代码, 在 hello 之前执行的")
fun()
print("我是装饰器1中的代码, 在 hello 之后...执行的")
return new_hello
else:
return fun
def strong2(fun):
def new_hello():
print("哈哈哈")
fun()
return new_hello
@strong2
@strong1
def hello():
print("我是 hello 函数中的代码")
# 这里调用的其实是装饰器返回的函数.
hello()
说明:
按照添加顺序: hello = strong2(strong1(hello))