装饰器的嵌套
# 装饰器A
def testA(fun_A):
def A_inner():
print('this is A 1')
fun_A()
print('this is A 2')
return A_inner
# 装饰器B
def testB(fun_B):
def B_inner():
print('this is B 3')
fun_B()
print('this is B 4')
return B_inner
# 当 @ 的下一行不是函数时,@ 会暂停执行
# @testB 装饰的是(@testA \n def demo():)这个整体
@testB # testB 再装饰前面得到的新 demo,返回了 B_inner,得到经过两次装饰的 demo
@testA # 先使用 testA 装饰 demo,返回了 A_inner,得到新的 demo
def demo():
print('demo 5')
demo()
'''
调用 demo() 时的执行过程
demo() ==> testB()
==> 3
==> fun_B()
==> 1
==> fun_A() ==> 5
==> 2
==> 4
'''
this is B 3
this is A 1
demo 5
this is A 2
this is B 4
# 装饰器1
def makeB(funcB):
def innerB():
return '<b>'+ funcB() +'</b>'
return innerB
# 装饰器2
def makeI(funcI):
def innerI():
return '<i>'+ funcI() +'</i>'
return innerI
# 待修饰函数
@makeB
@makeI
def test():
return 'information management system'
res = test()
print(res)
<b><i>information management system</i></b>