<>需求?多个装饰器作用于一个函数,比如有两个装饰器@login, @allow,想先判断用户是否登陆,然后再判断用户是否有权限

<>一个示例解释python装饰器的执行顺序(抄别人的),这里有个问题所以记下来
def decorator_a(func): print('Get in decorator_a') def
inner_a(*args,**kwargs): print('Get in inner_a') res = func(*args,**kwargs)
return res return inner_a def decorator_b(func): print('Get in decorator_b')
def inner_b(*args,**kwargs): print('Get in inner_b') res = func(*args,**kwargs)
return res return inner_b @decorator_b @decorator_a def f(x): print('Get in f')
return x * 2
结果
Get in decorator_a
Get in decorator_b

<>
看起来,装饰器在函数定义时已经开始倒序执行。这里如果是用decorator_b(decorator_a(f)),得到的结果也是同样的。但这里有个问题,如果我再新建一个带参数的装饰器C
def decorator_c(nums): print("Get in decorator_c") def wrapper(func):
print("Get in wrapper_c") def inner_c(*args, **kwargs): print('Get in inner_c')
res = func(*args, **kwargs)+nums return res return inner_c return wrapper
@decorator_c(10) @decorator_b @decorator_a def f(x): print('Get in f') return x
* 2
<>这时候得到的执行结果是

Get in decorator_c
Get in decorator_a
Get in decorator_b
Get in wrapper_c

<>这是定义时的执行顺序,执行时的循序才是最重要的,执行f(1).

Get in inner_c
Get in inner_b
Get in inner_a
Get in f
很明显,经过一系列的装饰器定义,现在的函数大概可以这样表示:inner_c(… return inner_b(… return
inner_a(…return f(1)))), 在inner_c中返回的func是inner_b,inner_b返回的是inner_a,
inner_a返回f,inner_c —>inner_b —>inner_a ,顺序执行,inner_c的装饰部分代码首先执行。
所以如果需要实现,先登陆再判断权限,应该
@login
@allow
def get_user_department():
pass

技术
今日推荐
PPT
阅读数 99
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信