
python装饰器讲解
发布日期:2021-05-14 15:03:32
浏览次数:19
分类:精选文章
本文共 1856 字,大约阅读时间需要 6 分钟。
Python 装饰器讲解
装饰器的基本概念
装饰器是一种在不改变原函数功能的前提下,向函数中注入额外功能或改变其行为的技术。通过使用装饰器,可以在代码中添加新的功能,简化代码管理流程。
以计算函数运行时间为例
在实际编程中,装饰器的应用场景非常多。以下是一个典型的例子:计算函数运行时间。
第一次尝试
import timedef index(): time.sleep(2)start_time = time.time()index()end_time = time.time()print(end_time - start_time)
这个代码直接使用time.time()
和time.sleep()
来计算函数运行时间,但实现简单,难以扩展。
第二次优化
import timedef index(): time.sleep(2)def calculate_time(f): start_time = time.time() f() end_time = time.time() print(end_time - start_time)calculate_time(index)
这个版本通过将index
函数传递给calculate_time
函数,实现了时间计算的功能,但仍然不够灵活。
第三次优化
import timedef index(): time.sleep(2)def calculate_time(f): start_time = time.time() f() end_time = time.time() print(end_time - start_time)calculate_time(index)
这个版本引入了函数inner
,使得装饰器能够更灵活地处理函数调用。
第四次优化
import timedef index(): time.sleep(2)def calculate_time(f): def inner(): start_time = time.time() f() end_time = time.time() print(end_time - start_time) return innerindex = calculate_time(index)
这个版本将calculate_time
转换成了一个装饰器,通过@calculate_time
语法糖实现,更方便阅读。
第五次优化
import timedef calculate_time(f): def inner(*args, **kwargs): start_time = time.time() ret = f(*args, **kwargs) end_time = time.time() print(end_time - start_time) return ret return inner@calculate_timedef add(x, y): time.sleep(2) return x + yprint(add(3, 3))
这个版本支持函数的传参,更加灵活实用。
真正的装饰器(加上传递参数)
import timedef calculate_time(f): def inner(*args, **kwargs): start_time = time.time() ret = f(*args, **kwargs) end_time = time.time() print(end_time - start_time) return ret return inner@calculate_timedef add(x, y): time.sleep(2) return x + yprint(add(3, 3))
这个实现支持任意函数参数,展示了装饰器的实际应用场景。
总结
通过以上例子可以看出,装饰器是一种强大的功能扩展工具,能够在不改变原函数的前提下,灵活地添加功能。通过将函数传递给装饰器,可以实现对代码行为的丰富扩展,简化代码管理,提高代码复用性。
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年05月08日 22时45分39秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Linux终端调试大全(非常详细)零基础入门到精通,收藏这一篇就够了
2023-02-05
Linux经典系统故障汇总与排障技巧及排障汇总表
2023-02-05
Linux经常使用命令(一) - ls
2023-02-05
Linux经常使用命令(十一) - more
2023-02-05
Linux经常使用命令(十二) - less
2023-02-05
linux经常使用(一)linux 安装配置 jdk之 找不到安装文件文件夹及source /etc/profile 报unexpected end of file 错误 解决...
2023-02-05
linux给用户改变组,Linux用户及用户组的建立,修改和删除
2023-02-05
linux给用户添加sudo权限
2023-02-05
linux缓存nscd
2023-02-05
linux编写一个简单的端口扫描程序,LINUX端口扫描源代码(C实现)
2023-02-05
linux编程之信号量
2023-02-05
LINUX编程实战指发送UDP消息
2023-02-05
linux编程:getenv,putenv,setenv
2023-02-05
linux编译ffmpeg2.6.2
2023-02-05
linux编译升级应用,Linux如何升级软件版本
2023-02-05
linux编译注解
2023-02-05