栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

记忆到磁盘-python-永久记忆

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

记忆到磁盘-python-永久记忆

Python提供了一种非常优雅的方式来执行此操作-装饰器。基本上,装饰器是一个包装另一个功能以提供其他功能而不更改功能源代码的功能。您的装饰器可以这样写:

import jsondef persist_to_file(file_name):    def decorator(original_func):        try: cache = json.load(open(file_name, 'r'))        except (IOError, ValueError): cache = {}        def new_func(param): if param not in cache:     cache[param] = original_func(param)     json.dump(cache, open(file_name, 'w')) return cache[param]        return new_func    return decorator

一旦知道了,就可以使用@ -syntax“装饰”函数,您就可以准备就绪了。

@persist_to_file('cache.dat')def html_of_url(url):    your function pre...

请注意,此修饰器是有意简化的,可能不适用于所有情况,例如,当源函数接受或返回无法进行json序列化的数据时。

有关装饰器的更多信息:如何制作功能装饰器链?

这是使装饰器在退出时仅保存一次缓存的方法:

import json, atexitdef persist_to_file(file_name):    try:        cache = json.load(open(file_name, 'r'))    except (IOError, ValueError):        cache = {}    atexit.register(lambda: json.dump(cache, open(file_name, 'w')))    def decorator(func):        def new_func(param): if param not in cache:     cache[param] = func(param) return cache[param]        return new_func    return decorator


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/668277.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号