python函数装饰器之带参数的函数和带参数的装饰器用法示例
作者:weixin_42359464 时间:2022-02-14 08:43:40
本文实例讲述了python函数装饰器之带参数的函数和带参数的装饰器用法。分享给大家供大家参考,具体如下:
1. 函数带多个参数
# 普通的装饰器, 打印函数的运行时间
def decrator(func):
def wrap(*args, **kwargs):
start_time = time.time()
res = func(*args, **kwargs)
end_time = time.time()
print('运行时间为', end_time-start_time)
return res
return wrap
2. 装饰器带有多个参数
当装饰器带有多个参数的时候, 装饰器函数就需要多加一层嵌套:
比如:
def decrator(*dargs, **dkargs):
def wrapper(func):
def _wrapper(*args, **kargs):
print ("装饰器参数:", dargs, dkargs)
print ("函数参数:", args, kargs)
return func(*args, **kargs)
return _wrapper
return wrapper
为什么被装饰函数体可以传入内层呢?
装饰器函数有多个参数, 需要以@decrator(1, a=2)
的方式使用, 这时候decrator是已经执行的(因为加了括号), 可以粗略的理解为加载被装饰函数的上的是wrapper, 所以这和普通的装饰器并无差别.
又如flask源码中的:
def route(self, rule, **options):
"""Like :meth:`Flask.route` but for a blueprint. The endpoint for the
:func:`url_for` function is prefixed with the name of the blueprint.
"""
def decorator(f):
endpoint = options.pop("endpoint", f.__name__)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
flask的蓝图route源码中的装饰器, 最内层直接返回return f 并没有多加一层处理的函数, 在无需对被装饰函数进行过多处理的时候这是较为方便的做法. route源码中只是对装饰器参数进行了处理.
关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/weixin_42359464/article/details/80671769
标签:python,函数装饰器,带参数的函数,带参数的装饰器
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
超详细注释之OpenCV制作图像Mask
2021-10-20 14:15:34
![](https://img.aspxhome.com/file/2023/3/98793_0s.jpg)
javascript动态添加单元格的脚本代码
2023-09-02 05:21:26
对Python获取屏幕截图的4种方法详解
2023-11-19 09:45:41
如何让shell终端和goland控制台输出彩色的文字
2023-07-13 03:24:56
![](https://img.aspxhome.com/file/2023/9/87629_0s.jpg)
python中format的用法实例详解
2023-08-03 12:27:28
网页设计:巧用记事本编辑网页
2008-02-05 09:00:00
pyecharts调整图例与各板块的位置间距实例
2023-05-15 20:05:40
![](https://img.aspxhome.com/file/2023/2/76762_0s.jpg)
Python中的“_args”和“__kwargs”用法详解
2023-03-11 02:10:38
Python unittest装饰器实现原理及代码
2022-05-06 22:33:49
这三个好用的python函数你不能不知道!
2023-04-23 10:29:22
![](https://img.aspxhome.com/file/2023/8/107868_0s.png)
python采用django框架实现支付宝即时到帐接口
2023-07-16 00:15:33
keras中模型训练class_weight,sample_weight区别说明
2021-09-17 06:23:18
python 实现docx与doc文件的互相转换
2022-01-19 06:45:58
![](https://img.aspxhome.com/file/2023/3/76083_0s.jpg)
python中显存回收问题解决方法
2022-06-28 03:06:29
pycharm快捷键汇总
2022-12-30 22:43:40
![](https://img.aspxhome.com/file/2023/7/79417_0s.jpg)
Python调用shell命令常用方法(4种)
2021-05-06 08:22:06
![](https://img.aspxhome.com/file/2023/8/76188_0s.png)
代码总结Python2 和 Python3 字符串的区别
2023-05-25 00:58:52
python爬虫爬取淘宝商品信息(selenum+phontomjs)
2022-07-07 05:40:52
![](https://img.aspxhome.com/file/2023/9/72869_0s.jpg)
pycharm创建并使用虚拟环境的详细图文教程
2022-05-27 18:19:51
![](https://img.aspxhome.com/file/2023/8/120288_0s.png)
儿童python练习实例
2023-12-13 04:26:32