首次使用后重新分配时,局部变量出现 UnboundLocalError [英] UnboundLocalError on local variable when reassigned after first use
问题描述
以下代码在 Python 2.5 和 3.0 中均按预期工作:
The following code works as expected in both Python 2.5 and 3.0:
a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
但是,当我取消注释 (B) 行时,我在 (A) 行收到 UnboundLocalError: 'c' not assignment
.a
和 b
的值打印正确.这让我完全困惑,原因有两个:
However, when I uncomment line (B), I get an UnboundLocalError: 'c' not assigned
at line (A). The values of a
and b
are printed correctly. This has me completely baffled for two reasons:
为什么会因为 (B) 行后面的语句而在 (A) 行抛出运行时错误?
Why is there a runtime error thrown at line (A) because of a later statement on line (B)?
为什么变量 a
和 b
按预期打印,而 c
会引发错误?
Why are variables a
and b
printed as expected, while c
raises an error?
我能想到的唯一解释是local变量c
是由赋值c+=1
创建的,它优先甚至在创建局部变量之前就覆盖了全局"变量 c
.当然,在变量存在之前窃取"作用域是没有意义的.
The only explanation I can come up with is that a local variable c
is created by the assignment c+=1
, which takes precedent over the "global" variable c
even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists.
有人可以解释一下这种行为吗?
Could someone please explain this behavior?
推荐答案
Python 以不同的方式处理函数中的变量,具体取决于您是从函数内部还是外部为其赋值.如果在函数内分配了变量,则默认情况下将其视为局部变量.因此,当您取消注释该行时,您试图在为其分配任何值之前引用局部变量 c
.
Python treats variables in functions differently depending on whether you assign values to them from inside or outside the function. If a variable is assigned within a function, it is treated by default as a local variable. Therefore, when you uncomment the line you are trying to reference the local variable c
before any value has been assigned to it.
如果想让变量c
引用函数前赋值的全局c=3
,把
If you want the variable c
to refer to the global c = 3
assigned before the function, put
global c
作为函数的第一行.
至于 python 3,现在有
As for python 3, there is now
nonlocal c
您可以使用它来引用最近的具有 c
变量的封闭函数作用域.
that you can use to refer to the nearest enclosing function scope that has a c
variable.
这篇关于首次使用后重新分配时,局部变量出现 UnboundLocalError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!