为什么会这样:
def fn(proc, *args, **kwargs):
cache = proc.cache = {}
def cached_execution(cache, *args, **kwargs):
if proc in cache:
if args in cache[proc]:
return cache[proc][args]
res = proc(args)
cache[proc] = {args: res}
return res
return cached_execution(cache, proc, *args, **kwargs)
@fn
def cached_fibo(n):
if n == 1 or n == 0:
return n
else:
return cached_fibo(n-1) + cached_fibo(n-2)
print cached_fibo(100)
抛出这样的异常:
NameError: global name 'cached_fibo' is not defined
我缺少什么基本概念?
(从概念上讲,**kwargs
仅用于装饰。不用于检索缓存结果,但不用担心)。
最佳答案
装饰器应该返回一个函数,而不是调用函数的结果。
但这会导致我们犯下一个错误:当您将 cache
和 proc
传递给 cached_execution
函数时,它们会落在 *args< 中
又被传递给 proc
。这没有道理。只需让 cache
和 proc
在内部方法中被捕获即可:
def fn(proc, *args, **kwargs):
cache = proc.cache = {}
def cached_execution(*args, **kwargs):
if proc in cache:
if args in cache[proc]:
return cache[proc][args]
res = proc(*args)
cache[proc] = {args: res}
return res
return cached_execution
另一个问题:您没有解压args
。您应该调用 proc(*args)
而不是 proc(args)
(上面已修复)。
关于python - 使用装饰器在定义的函数上产生 NameError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32229767/