【问题标题】:how to memoize a function result in python?如何在python中记住函数结果?
【发布时间】:2015-05-26 03:27:30
【问题描述】:

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

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)

【问题讨论】:

标签: python memoization


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    成员函数不能使用类装饰器,应该使用函数装饰器:

    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
    

    【讨论】:

      猜你喜欢
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      • 2020-08-01
      • 2015-12-11
      相关资源
      最近更新 更多