以下闭包函数在 javascript 中运行良好。
function generateNextNumber(startNumber) {
var current = startNumber;
return function(){
return current += 1;
}
}
var getNextNumber = generateNextNumber(10);
for (var i = 0; i < 10; i++) {
console.log(getNextNumber());
}
我尝试在 Python 中做同样的事情
def generateNextNumber(startNumber):
current = startNumber
def tempFunction():
current += 1
return current
return tempFunction
getNextNumber = generateNextNumber(10)
for i in range(10):
print (getNextNumber())
我收到以下错误
Traceback (most recent call last):
File "/home/thefourtheye/Desktop/Test1.py", line 10, in <module>
print (getNextNumber())
File "/home/thefourtheye/Desktop/Test1.py", line 4, in tempFunction
current += 1
UnboundLocalError: local variable 'current' referenced before assignment
当我打印vars()
and locals()
insidetempFunction
时,他们确认current
存在。
({'current': 10}, {'current': 10})
但是当我像这样修改程序时
def generateNextNumber(startNumber):
current = {"Number" : startNumber}
def tempFunction():
current["Number"] += 1
return current["Number"]
return tempFunction
有用。我无法解释为什么会这样。谁能解释一下?