不明白为什么会发生UnboundLocalError(关闭) [英] Don't understand why UnboundLocalError occurs (closure)
问题描述
我在这里做什么错了?
counter = 0
def increment():
counter += 1
increment()
以上代码抛出 UnboundLocalError
。
推荐答案
Python没有变量声明,因此必须找出变量本身的范围。它通过一个简单的规则来执行此操作:如果在函数内部对变量进行了赋值,则该变量被视为局部变量。 [1] 因此,该行
Python doesn't have variable declarations, so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.[1] Thus, the line
counter += 1
隐含 counter
在 increment()
本地。但是,尝试执行此行将尝试在分配局部变量 counter
之前读取它的值,从而导致 UnboundLocalError
。 [2]
implicitly makes counter
local to increment()
. Trying to execute this line, though, will try to read the value of the local variable counter
before it is assigned, resulting in an UnboundLocalError
.[2]
如果计数器
是全局变量,则 global
关键字会有所帮助。如果 increment()
是局部函数,而 counter
是局部变量,则可以使用 nonlocal
在Python 3.x中。
If counter
is a global variable, the global
keyword will help. If increment()
is a local function and counter
a local variable, you can use nonlocal
in Python 3.x.
这篇关于不明白为什么会发生UnboundLocalError(关闭)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!