Python 多级装饰器原理分析

import time

def ouou(func):
    print('555555')
    def wrapper(x,**A):
        print('22222222222')
        time.sleep(2)
        print('22222222222')
        func(x,**A)
    print('5555552')
    return wrapper

def ouou2(func):
    print('4444444')
    def wrapper(x,**A):
        func(x,**A)
        print('11111111')
        time.sleep(2)
        print('11111111')
    print('44444442')
    return wrapper

@ouou2
@ouou
def test(n,clazz='666'):
    print(n)
    print(clazz)

a=10
test(a,clazz='777')

在这里插入图片描述
在这里插入图片描述
顺序流程如下:

装载ouou函数
所以会先打印
555555
55555552
把被装饰函数test 替换为ouou的wrapper

装载ouou2
444444
44444442
把被装饰函数test 替换为ouou2的wrapper

执行test,此时test指向ouou2的wrapper
执行ouou2的wrapper

ouou2的wrapper中的func指向ouou的wrapper
2222222222
2222222222

ouou的wrapper的func为test
10 777

上述执行完返回ouou2的wrapper,往下执行
111111111
111111111

猜你喜欢

转载自blog.csdn.net/weixin_44291381/article/details/113695584