python如何修改装饰器中参数
作者:北门吹雪 时间:2021-08-18 15:28:27
本文实例为大家分享了python修改装饰器中参数的具体代码,供大家参考,具体内容如下
案例:
为分析程序内哪些函数执行时间开销较大,我们需定义一个带timeout参数的装饰器
需求:
统计被装饰函数的运行时间
时间大于timeout时,将此次函数调用记录到log日志中
运行时可以修改timeout的值
如何解决这个问题?
定义一个装饰器,计算函数执行时间,并与timeout比较,当大于timeout时候,通过logging模块打印出日志信息
在包裹函数中添加一个函数,通过这个函数来修改timeout变量
在python3中用nonlocal来声明嵌套作用域中的变量引用,在python2中可以通过把timeout参数变成列表,通过列表索引来进行改值
#!/usr/bin/python3
import time
import logging
from random import randint
def run_time(timeout):
"""
定义检查函数运行时间,并打印对应函数运行时间超出设定时间日志,并支持更改timeout
"""
# python2
# timeout = [timeout]
# 真正包裹函数
def out_wrapper(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
used_time = time.time() - start_time
# 对于超出timeout的函数进行日志打印
if used_time > timeout:
msg = '%s: %s > %s' % (func.__name__, used_time, timeout)
logging.warn(msg)
# python2
# if used_time > timeout[0]:
# msg = '%s: %s > %s' % (func.__name__, used_time, timeout[0])
# logging.warn(msg)
# return result
# 设置timeout参数值
def set_timeout(value):
nonlocal timeout
timeout = value
wrapper.set_timeout = set_timeout
# python2
# def set_timeout(value):
# timeout[0] = value
# wrapper.set_timeout = set_timeout
return wrapper
return out_wrapper
@run_time(1.5)
def func():
# 随机有50%的几率程序沉睡1秒
while randint(0, 1):
time.sleep(1)
print('func_run')
if __name__ == "__main__":
for _ in range(10):
func()
print('_'*50)
# 更改run_time装饰器中timeout参数
func.set_timeout(2)
for _ in range(10):
func()
来源:http://www.cnblogs.com/2bjiujiu/p/7293912.html
标签:python,装饰器,参数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
解决jupyter (python3) 读取文件遇到的问题
2021-02-05 10:00:25
Python基于最小二乘法实现曲线拟合示例
2021-08-06 15:47:07
![](https://img.aspxhome.com/file/2023/8/67348_0s.png)
Python批量启动多线程代码实例
2021-09-01 04:41:16
display:inline问题小结
2008-05-01 13:08:00
Python3安装模块报错Microsoft Visual C++ 14.0 is required的解决方法
2021-02-14 00:18:22
![](https://img.aspxhome.com/file/2023/3/76023_0s.png)
SQL Server用触发器强制执行业务规则
2009-01-20 16:05:00
Python制作简易版小工具之计算天数的实现思路
2023-10-29 08:12:07
![](https://img.aspxhome.com/file/2023/4/91874_0s.png)
使用python 打开文件并做匹配处理的实例
2022-01-15 16:27:30
Python 制作查询商品历史价格的小工具
2021-10-13 06:03:16
![](https://img.aspxhome.com/file/2023/3/84883_0s.png)
详解python中的json的基本使用方法
2022-03-15 22:29:13
Django crontab定时任务模块操作方法解析
2022-08-01 03:50:56
Python GUI学习之登录系统界面篇
2023-01-06 14:32:42
![](https://img.aspxhome.com/file/2023/2/72222_0s.png)
python 随机生成10位数密码的实现代码
2021-08-01 23:49:02
ASP连接Access数据库和SQL server数据库的方法
2007-08-22 13:16:00
SQL处理多级分类,查询结果呈树形结构
2012-08-21 10:50:12
使用Python三角函数公式计算三角形的夹角案例
2022-12-06 04:09:33
Pytorch模型定义与深度学习自查手册
2023-02-11 18:30:27
![](https://img.aspxhome.com/file/2023/7/90417_0s.png)
Django实现上传图片功能
2022-01-06 13:57:44
![](https://img.aspxhome.com/file/2023/4/66364_0s.jpg)
python使用re模块爬取豆瓣Top250电影
2023-10-11 17:28:38
![](https://img.aspxhome.com/file/2023/0/82650_0s.png)
SQLServer 存储过程简介与使用方法
2009-07-07 14:06:00