我哪里做错了?

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'

其他回答

试试这个:

counter = 0

def increment():
  global counter
  counter += 1

increment()

你需要使用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)

要回答主题行中的问题,是的,Python中有闭包,只是它们只应用于函数内部,而且(在Python 2.x中)它们是只读的;不能将名称重新绑定到不同的对象(但如果对象是可变的,则可以修改其内容)。在Python 3中。X,您可以使用nonlocal关键字来修改闭包变量。

def incrementer():
    counter = 0
    def increment():
        nonlocal counter
        counter += 1
        return counter
    return increment

increment = incrementer()

increment()   # 1
increment()   # 2

*这个问题最初问的是Python中的闭包。