我在这里做错了什么?
counter = 0
def increment():
counter += 1
increment()
上面的代码抛出了一个UnboundLocalError
。
发布于 2012-02-14 01:13:58
您需要使用global statement,以便修改全局变量计数器,而不是局部变量:
counter = 0
def increment():
global counter
counter += 1
increment()
如果定义counter
的封闭作用域不是全局作用域,那么在Python3.x上可以使用nonlocal statement。在Python2.x上,在同样的情况下,您将无法重新分配非本地名称counter
,因此您需要将counter
设置为可变名称并对其进行修改:
counter = [0]
def increment():
counter[0] += 1
increment()
print counter[0] # prints '1'
发布于 2012-02-14 01:21:14
为了回答主题行中的问题,*是的,Python中有闭包,只是它们只适用于函数内部,而且(在Python2.x中)闭包是只读的;您不能将名称重新绑定到不同的对象(但如果对象是可变的,则可以修改其内容)。在Python3.x中,可以使用nonlocal
关键字修改闭包变量。
def incrementer():
counter = 0
def increment():
nonlocal counter
counter += 1
return counter
return increment
increment = incrementer()
increment() # 1
increment() # 2
*这个问题最初是关于Python中的闭包。
发布于 2012-02-14 01:31:13
代码抛出UnboundLocalError
的原因已经在其他答案中得到了很好的解释。
但在我看来,您正在尝试构建像itertools.count()
一样工作的东西。
所以你为什么不尝试一下,看看它是否适合你的情况:
>>> from itertools import count
>>> counter = count(0)
>>> counter
count(0)
>>> next(counter)
0
>>> counter
count(1)
>>> next(counter)
1
>>> counter
count(2)
https://stackoverflow.com/questions/9264763
复制相似问题