十二、装饰器 2.装饰器的嵌套

2021/12/15 6:17:53

本文主要是介绍十二、装饰器 2.装饰器的嵌套,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

装饰器的嵌套

# 装饰器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>


这篇关于十二、装饰器 2.装饰器的嵌套的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程