python中多个装饰器的执行顺序详解
作者:wyzane 时间:2022-04-30 13:43:51
装饰器是程序开发中经常会用到的一个功能,也是python语言开发的基础知识,如果能够在程序中合理的使用装饰器,不仅可以提高开发效率,而且可以让写的代码看上去显的高大上^_^
使用场景
可以用到装饰器的地方有很多,简单的举例如以下场景
引入日志
函数执行时间统计
执行函数前预备处理
执行函数后清理功能
权限校验等场景
缓存
今天讲一下python中装饰器的执行顺序,以两个装饰器为例。
装饰器代码如下:
def wrapper_out1(func):
print('--out11--')
def inner1(*args, **kwargs):
print("--in11--")
ret = func(*args, **kwargs)
print("--in12--")
return ret
print("--out12--")
return inner1
def wrapper_out2(func):
print('--out21--')
def inner2(*args, **kwargs):
print("--in21--")
ret = func(*args, **kwargs)
print("--in22--")
return ret
print("--out22")
return inner2
@wrapper_out2
@wrapper_out1
def test():
print("--test--")
return 1 * 2
if __name__ == '__main__':
test()
执行结果如下:
"""
--out11--
--out12--
--out21--
--out22--
--in21--
--in11--
--test--
--in12--
--in22--
"""
执行顺序以图片形式展示如下:
先进入离test函数最近的装饰器,由于装饰器中返回的是函数的函数名引用,并非真正调用函数,所以先打印:
--out11--
--out12--
--out21--
--out22--
到inner2后,func会真正执行函数,会调用inner1(),所以再打印:
--in21--
--in11--
到inner1中,func会调用test函数,所以会打印:
--test--
再从各个函数出来后,会依次打印:
--in12--
--in22--
合起来就是上面的执行结果。
来源:https://segmentfault.com/a/1190000016603109
标签:python,多装饰器,执行顺序
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
解决python3 HTMLTestRunner测试报告中文乱码的问题
2021-10-19 04:34:06
纠结于ajax开发中 response的contentType 问题
2008-12-11 13:46:00
SQL Server如何实现快速删除重复记录?
2011-05-03 11:18:00
使用python处理题库表格并转化为word形式的实现
2023-07-25 12:33:18
![](https://img.aspxhome.com/file/2023/5/61175_0s.jpg)
python中的代码编码格式转换问题
2022-02-26 02:05:02
python使用pandas读xlsx文件的实现
2021-01-21 05:00:10
![](https://img.aspxhome.com/file/2023/9/79669_0s.jpg)
Python插入Elasticsearch操作方法解析
2021-08-30 01:47:09
asp如何使用SMTP Service发送邮件?
2010-06-05 12:43:00
MYSQL5 下的兼容说明(my.ini my.conf)
2008-02-23 10:13:00
Python 作为小程序后端的三种实现方法(推荐)
2023-03-30 09:26:05
![](https://img.aspxhome.com/file/2023/1/101621_0s.jpg)
Go语言算法之寻找数组第二大元素的方法
2023-06-24 16:19:03
python中安装Scrapy模块依赖包汇总
2023-11-08 07:06:25
Python中定时任务框架APScheduler的快速入门指南
2021-07-16 02:51:21
Python处理yaml和嵌套数据结构技巧示例
2023-10-18 04:33:37
![](https://img.aspxhome.com/file/2023/5/85145_0s.png)
超强多功能php绿色集成环境详解
2023-07-15 01:07:22
![](https://img.aspxhome.com/file/2023/2/55472_0s.jpg)
自动清空站点目录下所有文件
2009-06-24 11:11:00
Python编解码问题及文本文件处理方法详解
2021-04-13 07:52:06
![](https://img.aspxhome.com/file/2023/9/72999_0s.png)
asp是的日期转换为星座的函数
2011-02-26 11:11:00
说说值类型数据“.”操作符的类型转换
2009-12-13 10:39:00
教你利用python如何读取txt中的数据
2023-04-03 14:52:36
![](https://img.aspxhome.com/file/2023/0/66420_0s.png)