Python提供了一种非常优雅的方式来执行此操作-装饰器。基本上,装饰器是一个包装另一个功能以提供其他功能而不更改功能源代码的功能。您的装饰器可以这样写:
import json
def 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 code...
请注意,此修饰器是有意简化的,可能不适用于所有情况,例如,当源函数接受或返回无法进行json序列化的数据时。
import json, atexit
def 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