我刚开始使用Python,我不知道什么是memoization以及如何使用它.另外,我可以有一个简化的例子吗?
我有一个runquery调用函数,它调用数据库,然后逐个产生行.我写了一个memoize装饰器(或者更确切地说,我只是从这个stackoverflow问题中偷走了一个)但是在后续调用中它只产生一个空序列,大概是因为生成器的值只能产生一次.
我怎么能修改适用于Python生成器的memoization装饰器?我意识到我需要在某些时候将它存储在内存中,但我想在装饰器中处理它而不是修改原始函数.
memoization函数的当前代码是:
def memoized(f):
# Warning: Doesn't work if f yields values
cache={}
def ret(*args):
if args in cache:
return cache[args]
else:
answer=f(*args)
cache[args]=answer
return answer
return ret
Run Code Online (Sandbox Code Playgroud) 我有这段代码:
#!/usr/bin/env python
def get_match():
cache=[]
def match(v):
if cache:
return cache
cache=[v]
return cache
return match
m = get_match()
m(1)
Run Code Online (Sandbox Code Playgroud)
如果我运行它,它说:
UnboundLocalError: local variable 'cache' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
但如果我这样做:
#!/usr/bin/env python
def get():
y = 1
def m(v):
return y + v
return m
a=get()
a(1)
Run Code Online (Sandbox Code Playgroud)
它运行.
列表中有什么东西吗?或者我的代码组织错了?