不明白为什么会出现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]
如果 counter
是一个全局变量,global
关键字会有所帮助.如果 increment()
是局部函数而 counter
是局部变量,则可以使用 nonlocal
.
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屋!