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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)