返回信息流如下代码:
def memo(fn):
cache = {}
@wraps(fn)
def wrapper(*args):
result = cache.get(args, None)
if result is None:
result = fn(*args)
cache[args] = result
return result
return wrapper
@memo
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
为什么局部变量cache不会每次重新生成,而是只会有一个?
然后改了下代码:
def memo(fn):
cache = {}
count = 1
@wraps(fn)
def wrapper(*args):
count += 1
result = cache.get(args, None)
# --同上,略--
这里就会报count未定义的错误
环境是python 2.7
求老司机解答, 感激不尽~
这是一条镜像帖。来源:北邮人论坛 / python / #14024同步于 2016/5/9
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
请教装饰器的问题
lecher
2016/5/9镜像同步3 回复
订阅后,新回复会通过你的通知中心匿名送达。
3 条回复
1. cache 在闭包创建时被捕获了
2. count 处改为
nonlocal count
count += 1
否则 count += 1 会使 count 绑定到一个新的 local variable,但你还没有给它值
3. 暖哥一定会建议你用 python 3
用python3吧
1. cache = {}里面的{}是在求值的时候创建一个dict。当然就是每调用一次memo创建一个啦。
2. 就是楼上说的。
【 在 Vampire 的大作中提到: 】
: 1. cache 在闭包创建时被捕获了
: 2. count 处改为
: nonlocal count
: ...................
thx,and thx 暖神~