问题描述
counter = 0
def increment():
counter + = 1
increment()
以上代码抛出一个 UnboundLocalError
。
Python没有变量声明,所以它必须找出变量本身的。它是通过一个简单的规则来实现的:如果函数内部有一个变量赋值,那么该变量被认为是本地的。因此,行
counter + = 1
隐含地使 counter
local to increment()
。尽管如此,试图执行这一行,会在分配之前尝试读取局部变量 counter
的值,导致。
如果 counter
是一个全局变量,则关键字将有所帮助。如果 increment()
是一个本地函数而 counter
是一个局部变量,则可以使用在Python 3.x中。
What am I doing wrong here?
counter = 0
def increment():
counter += 1
increment()
The above code throws a UnboundLocalError
.
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. Thus, the line
counter += 1
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
.
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.
这篇关于Python中的UnboundLocalError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!