码迷,mamicode.com
首页 > 其他好文 > 详细

多个装饰器执行顺序

时间:2018-06-08 20:31:48      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:style   some   rmi   something   required   perm   入参   word   mis   

多个装饰器的执行顺序

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

 

多个装饰器执行顺序

标签:style   some   rmi   something   required   perm   入参   word   mis   

原文地址:https://www.cnblogs.com/z-x-y/p/9157238.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!