Whenever you assign a variable inside of a function it will be a local variable for that function. The line start += 1
is assigning a new value to start
, so start
is a local variable. Since a local variable start
exists the function will not attempt to look in the global scope for start
when you first try to access it, hence the error you are seeing.
In 3.x your code example will work if you use the nonlocal
keyword:
def make_incrementer(start):
def closure():
nonlocal start
while True:
yield start
start += 1
return closure
On 2.x you can often get around similar issues by using the global
keyword, but that does not work here because start
is not a global variable.
In this scenario you can either do something like what you suggested (x = start
), or use a mutable variable where you modify and yield an internal value.
def make_incrementer(start):
start = [start]
def closure():
while True:
yield start[0]
start[0] += 1
return closure
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…