如何在python中记忆函数结果?

2024-06-16 10:50:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想记住类中函数的结果:

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)


Tags: 函数selfidsearchgetreturninitdef
2条回答

有几个例子是值得一看的记忆装饰器here。我认为第二个和第三个示例可能更好地解决了方法与函数之间的问题。在

成员函数不能使用类修饰符,应使用函数修饰符:

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

相关问题 更多 >