不明白为什么发生UnboundLocalError

不明白为什么发生UnboundLocalError 

我在这做错了什么?

counter = 0def increment():
  counter += 1increment()

上面的代码抛出了一个UnboundLocalError


RISEBY
浏览 1896回答 4
4回答

森林海

Python没有变量声明,因此必须弄清楚变量本身的范围。它通过一个简单的规则来实现:如果对函数内部的变量赋值,则该变量被视为本地变量。[1] 因此,这条线counter += 1隐含地使counter本地化increment()。但是,尝试执行此行将尝试counter在分配之前读取局部变量的值,从而产生一个UnboundLocalError。[2]如果counter是全局变量,global关键字将有所帮助。如果increment()是本地函数和counter局部变量,则可以nonlocal在Python 3.x中使用。

繁花不似锦

您需要使用全局语句,以便修改全局变量计数器,而不是局部变量:counter = 0def increment():   global counter   counter += 1increment()如果counter定义的封闭范围不是全局范围,则在Python 3.x上可以使用非本地语句。在Python 2.x的相同情况下,您将无法重新分配到非本地名称counter,因此您需要进行counter可变并修改它:counter = [0]def increment():   counter[0] += 1increment()print counter[0]  # prints '1'

拉风的咖菲猫

要回答主题中的问题,*是,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()   # 1increment()   # 2*原始问题的标题询问了Python中的闭包。

侃侃无极

您的代码抛出的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)
打开App,查看更多内容
随时随地看视频慕课网APP