Python装饰器功能介绍

发布时间:2021-09-03 14:41:56 作者:chen
来源:亿速云 阅读:122

这篇文章主要介绍“Python装饰器功能介绍”,在日常操作中,相信很多人在Python装饰器功能介绍问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Python装饰器功能介绍”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

示例:寻找宝藏。在一个嵌套元组tuple或列表list中寻找元素'Gold Coin'

import time
from functools import lru_cache
def find_treasure(box):
 for item in box:
  if isinstance(item, (tuple, list)):
   find_treasure(item)
  elif item == 'Gold Coin':
   print('Find the treasure!')
   return True
start = 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 - start
print('在没有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 True
start = 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 - start
print('在有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 2600
RAM:Kingston HyperX 8Gigabytes 2666

约使用7个月。

这个装饰器可以在函数运行时记录它的输入值与运行结果。当元组('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth')出现第二次时,加了这个装饰器的函数find_the_treasure_quickly不会再次在递归时对这个元组进行查找,而是直接在“备忘录”中找到运行结果并返回!

到此,关于“Python装饰器功能介绍”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. python装饰器的原理--装饰器过程
  2. Python中的装饰器详细介绍

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:css3中media响应式布局的示例分析

下一篇:MySQL中的隐藏列的具体查看方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》