我哪里做错了?
counter = 0
def increment():
counter += 1
increment()
上面的代码抛出一个UnboundLocalError。
我哪里做错了?
counter = 0
def increment():
counter += 1
increment()
上面的代码抛出一个UnboundLocalError。
当前回答
你需要使用global语句来修改全局变量计数器,而不是局部变量:
counter = 0
def increment():
global counter
counter += 1
increment()
如果定义计数器的封闭作用域不是全局作用域,则在Python 3上。你可以使用非局部语句。在Python 2中也是如此。X你将没有办法重新分配给非本地名称计数器,所以你需要使计数器可变并修改它:
counter = [0]
def increment():
counter[0] += 1
increment()
print counter[0] # prints '1'
其他回答
你需要使用global语句来修改全局变量计数器,而不是局部变量:
counter = 0
def increment():
global counter
counter += 1
increment()
如果定义计数器的封闭作用域不是全局作用域,则在Python 3上。你可以使用非局部语句。在Python 2中也是如此。X你将没有办法重新分配给非本地名称计数器,所以你需要使计数器可变并修改它:
counter = [0]
def increment():
counter[0] += 1
increment()
print counter[0] # prints '1'
要在函数中修改全局变量,必须使用global关键字。
当你试着不画线的时候
global counter
在增量定义的内部,创建了一个名为counter的局部变量,以防止弄乱整个程序可能依赖的计数器变量。
注意,只有在修改变量时才需要使用global;您可以从增量中读取counter,而不需要全局语句。
您的代码抛出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)
试试这个:
counter = 0
def increment():
global counter
counter += 1
increment()
Python不是纯粹的词法作用域。
参见在函数中使用全局变量。
和Python变量作用域注释。