不明白为什么会发生unbundLocalError

2024-04-26 23:47:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里做错什么了?

counter = 0

def increment():
  counter += 1

increment()

上面的代码抛出一个UnboundLocalError


Tags: 代码defcounterincrementunboundlocalerror
3条回答

您需要使用global statement来修改全局变量计数器,而不是局部变量:

counter = 0

def increment():
  global counter
  counter += 1

increment()

如果定义counter的封闭作用域不是全局作用域,那么在Python 3.x上可以使用nonlocal statement。在Python 2.x上的相同情况下,您将无法重新分配到非本地名称counter,因此需要使counter可变并修改它:

counter = [0]

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

increment()
print counter[0]  # prints '1'

要回答主题行中的问题,*yes,Python中有闭包,除了它们只应用于函数内部,而且(在Python 2.x中)它们是只读的;不能将名称重新绑定到其他对象(尽管如果对象是可变的,可以修改其内容)。在Python3.x中,可以使用^{}关键字修改闭包变量。

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

increment = incrementer()

increment()   # 1
increment()   # 2

*最初的问题是关于Python中的闭包。

Python没有变量声明,因此它必须计算出变量本身的scope。它是通过一个简单的规则来实现的:如果一个函数中有一个变量的赋值,那么这个变量就被认为是局部的

counter += 1

隐式地将counter设为increment()本地。但是,尝试执行这一行时,将尝试在分配局部变量之前读取它的值counter,从而产生^{}[2]

如果counter是全局变量,^{}关键字将有帮助。如果increment()是局部函数,而counter是局部变量,则可以在Python 3.x中使用^{}

相关问题 更多 >