1基本装饰
def deco_func(func):
def wrapper(*args,**kwargs):
print("我是装饰器")
print("我在被装饰函数执行之后,执行")
return func()
return wrapper
@deco_func
def funcA():
print(123)
funcA()
调用过程:
funcA=deco_func(func)
funcA()执行的是deco_func(func)返回值 wrapper()
结果:
我是装饰器
我在被装饰函数执行之后,执行
123
2.带参数装饰器
def deco_func(text):
print(text)
def decorator(func):
def wrapper(*args,**kwargs):
print("我是装饰器")
print("我在被装饰函数执行之后,执行")
return func()
return wrapper
return decorator
@deco_func("带参数")
def funcA():
print(123)
funcA()
funcA=deco_func("带参数")(funcA)
deco_func("带参数")返回decorator
相当于decorator(funcA)
decorator(funcA) 返回wrapper wrapper() 最终结果
结果:
带参数
我是装饰器
我在被装饰函数执行之后,执行
123
3.多个装饰器修饰
def funcA(func):
print("我是装饰器1")
def funcA_wraper(*args,**kwargs):
print("我是funcA_wraper")
func()
print("aaa")
return funcA_wraper
def funcB(func):
print("我是装饰器2")
def funcB_wraper(*args,**kwargs):
print("我是funcB_wraper")
func()
print("bbb")
return funcB_wraper
@funcA
@funcB
def funcC():
print("ccc")
funcC()
funcC=funcA(funcB(funcC))
先执行funcB(funcC)
打印:我是装饰器2 返回funcB_wraper
执行funcA(funcB_wraper)
打印:我是装饰器1 返回 funcA_wraper
执行funcC() 时执行的是funcA_wraper()
打印: "我是funcA_wraper"
遇到funcA_wraper的func实际上是funcB_wraper
执行funcB_wraper() 打印:"我是funcB_wraper"
遇到funcB_wraper()中的func() 实际是 funcC() 打印"ccc"
打印:"bbb" funcB_wraper()执行完毕回到funcA_wraper中继续执行
最后打印:"aaa"
结果:
我是装饰器2
我是装饰器1
我是funcA_wraper
我是funcB_wraper
ccc
bbb
aaa