我想在类中记住函数的结果:
class memoize:
def __init__(self, function):
self.function = function
self.memoized = {}
def __call__(self, *args):
try:
return self.memoized[args]
except KeyError, e:
self.memoized[args] = self.function(*args)
return self.memoized[args]
class DataExportHandler(Object):
...
@memoize
def get_province_id(self, location):
return search_util.search_loc(location)[:2] + '00000000'
def write_sch_score(self):
...
province_id = self.get_province_id(location)
但这不起作用,因为它告诉我get_province_id takes exactly 2 arguments(1 given)
答案 0 :(得分:0)
有一些值得一看的Memoizing装饰器here的例子。我认为第二个和第三个例子可能更好地解决方法与函数的问题。
答案 1 :(得分:-1)
成员函数不能使用类装饰器,你应该使用函数装饰器:
def memoize1(obj):
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
print 'not in cache'
cache[key] = obj(*args, **kwargs)
else:
print 'in cache'
return cache[key]
return memoizer