快上网专注成都网站设计 成都网站制作 成都网站建设
成都网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

Python装饰器功能介绍-创新互联

这篇文章主要介绍“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装饰器功能介绍”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注创新互联网站,小编会继续努力为大家带来更多实用的文章!


分享名称:Python装饰器功能介绍-创新互联
当前网址:http://6mz.cn/article/dcjjhj.html

其他资讯