这段 Python 代码不起作用:
def make_incrementer(start):
def closure():
# I know I could write 'x = start' and use x - that's not my point though (:
while True:
yield start
start += 1
return closure
x = make_incrementer(100)
iter = x()
print iter.next() # Exception: UnboundLocalError: local variable 'start' referenced before assignment
我知道如何修复那个错误,但请耐心等待:
这段代码正常工作:
def test(start):
def closure():
return start
return closure
x = test(999)
print x() # prints 999
为什么我可以在闭包中读取变量start
,但无法对其进行写入操作?是哪条语言规则导致了处理start
变量的这种方式?更新:我发现这个SO帖子很相关(答案比问题更相关):Read/Write Python Closures