相关疑难解决方法(0)

可以做些什么来加速这个memoization装饰器?

我想要的是一个memoization装饰器:

我已经调整了一个我看到的例子并想出了以下内容:

import functools

class Memoized(object):
  """Decorator that caches a function's return value each time it is called.
  If called later with the same arguments, the cached value is returned, and
  not re-evaluated.
  """

  __cache = {}

  def __init__(self, func):
    self.func = func
    self.key = (func.__module__, func.__name__)

  def __call__(self, *args):
    try:
      return Memoized.__cache[self.key][args]
    except KeyError:
      value = self.func(*args)
      Memoized.__cache[self.key] = {args : value}
      return value
    except TypeError:
      # uncachable -- …
Run Code Online (Sandbox Code Playgroud)

python memoization

3
推荐指数
1
解决办法
1610
查看次数

标签 统计

memoization ×1

python ×1