python笔记——多个decorator的执行顺序

事实上,用这样一段代码就能看出执行顺序:

def decorator_a(func):
    print('decorator a running.')

    def deco_a(*args, **kwargs):
        print('pretreatment a')
        res = func(*args, **kwargs)
        print('post processing a')
        return res

    print('decorator a finished.')
    return deco_a


def decorator_b(func):
    print('decorator b running.')

    def deco_a(*args, **kwargs):
        print('pretreatment b')
        res = func(*args, **kwargs)
        print('post processing b')
        return res

    print('decorator b finished.')
    return deco_a


@decorator_a
@decorator_b
def f(x):
    print('running f.')
    return x*2


print('')


def g(x):
    print('running g.')
    return x*3


g = decorator_a(g)
g = decorator_b(g)


print('')
print('\n', f(1), '\n')
print('\n', g(1), '\n')

 输出:

decorator b running.
decorator b finished.
decorator a running.
decorator a finished.

decorator a running.
decorator a finished.
decorator b running.
decorator b finished.

pretreatment a
pretreatment b
running f
post processing b
post processing a

 2 

pretreatment b
pretreatment a
get in g
post processing a
post processing b

 3 

首先,嵌套函数的外层内容在函数定义并装饰的过程中就已经被执行了。其次,装饰器的装饰顺序是靠近函数的装饰器先进行装饰,远离函数定义位置的装饰器后进行装饰。装饰函数内定义的函数定义之前的代码会在装饰过程中执行,而内层函数则会被返回给原函数。换而言之,在第一次装饰(@decorator_b)后,f已经变成了deco_b。而在第二次装饰时,相当于deco_b被传入decorator_a。装饰过程等于下列装饰函数调用

def i(x):
    return x*2


i = decorator_a(decorator_b(i))
print('')
print(i(1))

上述例子中,显示的,装饰过程也可以等价于下列过程:

print('decorator b running.')
print('decorator b finished.')
print('decorator a running.')
print('decorator a finished.')


def h(x):
    print('pretreatment a')
    print('pretreatment b')
    print('running h.')
    res = x*2
    print('post processing b')
    print('post processing a')
    return res


print(h(1), '\n')

而调用函数进行装饰则正好相反,调用过程是自上往下的,调用过程必须写在函数下方。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值