多个装饰器执行顺序

Posted When you look into the abyss,

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多个装饰器执行顺序相关的知识,希望对你有一定的参考价值。

多个装饰器的执行顺序

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#f=decorator_b(f)
@decorator_a#f=decorator_a(f)
def f(x):
    print Get in f
    return x * 2

"""

Get in decorator_a
Get in decorator_b

"""

等同于

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

def f(x):
    print(Get in f)
    return x * 2


f=decorator_a(f)
f=decorator_b(f)




"""

Get in decorator_a
Get in decorator_b

"""

得出结论 装饰器函数在被装饰函数定义好后立即执行 并且是从下往上执行,最后的两句代码等同于

f=decorator_b(decorator_a(f)),执行顺序是从里到外,最先调用最里层的装饰器,最后调用最外层的装饰器

 

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#f=decorator_b(f)
@decorator_a#f=decorator_a(f)
def f(x):
    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
"""

当我们对f传入参数1进行调用时,inner_b被调用了,他会先打印Get in inner_b,然后在inner_b内部调用了inner_a,所以会再打印Get in inner_a,然后再inner_a内部调用原来的f,并且将结果作为最终的返回

总结:

装饰器函数在被装饰函数定义好后立即执行从下往上执行

函数调用时从上到下执行

实际应用过程中,先验证有没有登录,在验证权限够不够,采用从上到下的顺序来装饰函数

@login_required
@permision_allowed
def f()
  # Do something
  return

 

以上是关于多个装饰器执行顺序的主要内容,如果未能解决你的问题,请参考以下文章

多个装饰器执行顺序

Python多个装饰器的顺序 转载

python多个装饰器的执行顺序

python多个装饰器的执行顺序

python多个装饰器的执行顺序

Django中视图的多个装饰器:执行顺序