Python装饰器功能介绍
发表于:2024-10-22 作者:千家信息网编辑
千家信息网最后更新 2024年10月22日,这篇文章主要介绍"Python装饰器功能介绍",在日常操作中,相信很多人在Python装饰器功能介绍问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"Python装饰器功能
千家信息网最后更新 2024年10月22日Python装饰器功能介绍
这篇文章主要介绍"Python装饰器功能介绍",在日常操作中,相信很多人在Python装饰器功能介绍问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"Python装饰器功能介绍"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
示例:寻找宝藏。在一个嵌套元组tuple或列表list中寻找元素'Gold Coin'
import timefrom functools import lru_cachedef find_treasure(box): for item in box: if isinstance(item, (tuple, list)): find_treasure(item) elif item == 'Gold Coin': print('Find the treasure!') return Truestart = time.perf_counter()find_treasure(('sth', 'sth', 'sth', ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'), ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'), 'Gold Coin', ))end = time.perf_counter()run_time_without_cache = end - startprint('在没有Cache的情况下,运行花费了{} s。'.format(run_time_without_cache))@lru_cache()def find_treasure_quickly(box): for item in box: if isinstance(item, (tuple, list)): find_treasure(item) elif item == 'Gold Coin': print('Find the treasure!') return Truestart = time.perf_counter()find_treasure_quickly(('sth', 'sth', 'sth', ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'), ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'), 'Gold Coin', ))end = time.perf_counter()run_time_with_cache = end - startprint('在有Cache的情况下,运行花费了{} s。'.format(run_time_with_cache))print('有Cache比没Cache快{} s。'.format(float(run_time_without_cache-run_time_with_cache)))
最终输出
Find the treasure!
在没有Cache的情况下,运行花费了0.0002182829999810565 s。
Find the treasure!
在有Cache的情况下,运行花费了0.00011638000000857573 s。
有Cache比没Cache快0.00010190299997248076 s。
注记:运行这个示例时我的电脑配置如下
CPU:AMD Ryzen 5 2600RAM:Kingston HyperX 8Gigabytes 2666
约使用7个月。
这个装饰器可以在函数运行时记录它的输入值与运行结果。当元组('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth')出现第二次时,加了这个装饰器的函数find_the_treasure_quickly
不会再次在递归时对这个元组进行查找,而是直接在"备忘录"中找到运行结果并返回!
到此,关于"Python装饰器功能介绍"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!
运行
功能
情况
学习
函数
更多
示例
结果
帮助
实用
接下来
元素
再次
备忘录
宝藏
文章
方法
理论
电脑
知识
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
互联网科技总结
人肺癌外泌体数据库
软件与应用技术和网络技术区别
软件开发怎么选笔记本
黄南州网络技术产品介绍
软件开发客户定位
恒生互联网科技基金
vs2008读取数据库的语句
洛阳招聘软件开发
搭建公司的web服务器产品介绍
悬架设计软件开发
电子科技大学无线互联网课程
正确道德取向成为网络安全主流
世纪佳缘网络安全中心
佛山武夷山软件开发
信息网络技术体会
上海天一电子科技互联网集团
戴尔服务器报警查询
王瑛玮公安部网络安全保卫局
营易网络技术公司
河南一览网络技术
数据库维护需要
flood防护服务器
未来之役连接不到服务器怎么回事
网络安全板块龙头股有哪些
饥荒服务器配置
江苏计算机软件开发价钱是多少
服务器上搭建linux操作系统
财务数据库怎么搭建
c语言从文档中读数据库