It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function.
在一个函数内部的某个地方,对一个变量通过赋值来修改的时候,遇到UnboundLocalError是让人非常吃惊的。
This code:
例如下面的代码:
>>> x = 10
>>> def bar():
... print x
>>> bar()
10
works, but this code:
运行成功,但是再往下看:
>>> x = 10
>>> def foo():
... print x
... x += 1
results in an UnboundLocalError:
出现了UNboundLocalError的错误:(有点意思的是,这个出错的地方是 print x 这行代码)
>>> foo()
Traceback (most recent call last):
...
UnboundLocalError: local variable 'x' referenced before assignment
This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x
, the compiler recognizes it as a local variable. Consequently when the earlier print x
attempts to print the uninitialized local variable and an error results.
这是由于在一个范围内,对一个变量进行赋值,这个变量变成该范围内的局部变量,会首先调用这个变量(而不会调用外部的相同变量名的变量),由于foo函数中最后一行代码对x赋了一个新值,编译器认为这是一个局部变量。因而,在之前对x尝试进行print的时候,会认为这是在print一个未被初始化的对象,所以出现了一个错误。
In the example above you can access the outer scope variable by declaring it global:
在上面的那个例子中,你可以将变量声明为global(全局变量)来对外部变量进行打印和修改
>>> x = 10
>>> def foobar():
... global x
... print x
... x += 1
>>> foobar()
10
This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope:
这个明显的声明是需要的:用来提醒你,你在修改外部变量的值
>>> print x
11