在我看来,您需要一些可以持久记忆的东西。这是基本的,但可能会让您入门:
import shelve
class MemoizedProcessor(object):
def __init__(self):
# writeback only if it can't be assured that you'll close this shelf.
self.preprocessed = shelve.open('preprocessed.cache', writeback = True)
if 'inputargs' not in self.preprocessed:
self.preprocessed['inputargs'] = dict()
def __del__(self, *args):
self.preprocessed.close()
def process(self, *args):
if args not in self.preprocessed['inputargs']:
self._process(*args)
return self.preprocessed['inputargs'][args]
def _process(self, *args):
# Something that actually does heavy work here.
result = args[0] ** args[0]
self.preprocessed['inputargs'][args] = result