【发布时间】:2015-03-24 14:22:53
【问题描述】:
我正在尝试为 memoize 编写 python 装饰器。 我有几个问题。
- @memoize 如何转换为 memoize 类的 call 函数?
- 为什么 init 需要一个参数。
- 缓存存储在哪里?它是与每个函数相关联还是全局变量?即如果我使用@memoize 会有两个缓存对象 多种功能。
..
class memoize:
def __init__(self):
self.cache = {}
def __call__(self, function):
def wrapper(*args, **kwargs):
key = str(function.__name__) + str(args) + str(kwargs)
if key in cache:
return cache[key]
else:
value = function(*args, **kwargs)
cache[key] = value
return value
return wrapper
@memoize
def fib(n):
if n in (0, 1):
return 1
else:
return fib(n-1) + fib(n-2)
for i in range(0, 10):
print(fib(i))
我收到编译错误。
Traceback (most recent call last):
File "memoize.py", line 17, in <module>
@memoize
TypeError: __init__() takes exactly 1 argument (2 given)
【问题讨论】:
-
你真的要从头开始写这个吗?
-
是的。我正在学习 python 装饰器
-
好的,仔细检查一下,因为有一个
lru_cache装饰器。
标签: python caching decorator python-decorators