多个装饰器修饰一个函数时的调用顺序

参考教程: https://blog.csdn.net/jyhhhhhhh/article/details/54627850

#当有多个装饰器装饰一个函数时,他们的执行顺序

#观察下方的代码就会发现
def decorator_a(func):
    print('Get in decorator_a')
    def inner_a(*args, **kwargs):
        print('Get in inner_a')
        return func(*args, **kwargs)
    return inner_a
 
def decorator_b(func):
    print('Get in decorator_b')
    def inner_b(*args, **kwargs):
        print('Get in inner_b')
        return func(*args, **kwargs)
    return inner_b
 
@decorator_b
@decorator_a
def f(x):
    #decorator_b(decorator_a(f))
    #而以上代码【decorator_b(decorator_a(f))】返回的是inner_b,所以执行的时候是先执行inner_b
    #然后在执行【decorator_a(f)】返回的inner_a  .最终在调用f(1)的时候,函数inner_b输出'Get in inner_b'
    #然后执行inner_a输出Get in decorator_a,最后执行func(),即f
    
    
    #调用时,函数的顺序
    '''
    @decorator_b
    @decorator_a
    def f(x)
    
    相当于-------decorator_b(decorator_a(f)),其中每一层返回的都是一个函数对象,没有调用
    之后返回时的函数对象--------inner_b(inner_a)
    然后最后一行当我们对 f 传入参数1进行调用时, inner_b 被调用了,它会先打印 Get in inner_b ,
    然后在 inner_b 内部调用了 inner_a 所以会再打印 Get in inner_a, 然后再 inner_a 内部调用的原来的 f, 
    并且将结果作为最终的返回
    '''
    print('Get in f')
    return x * 2
 
f(1)

输出结果
Get in decorator_a
Get in decorator_b
Get in inner_b
Get in inner_a
Get in f


实际中的使用
在实际应用的场景中,当我们采用上面的方式写了两个装饰方法,比如先验证有没有登录@login_required,
再验证权限够不够时@permision_allowed时,我们采用下面的顺序来装饰函数:

@login_required
@permision_allowed
def f()
  # Do something

  



猜你喜欢

转载自www.cnblogs.com/qingsheng/p/9629668.html