Python 范围:“UnboundLocalError:赋值前引用了局部变量‘c’”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/146359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python scope: "UnboundLocalError: local variable 'c' referenced before assignment"
提问by all-too-human
I am trying to figure out this:
我想弄清楚这一点:
c = 1
def f(n):
print c + n
def g(n):
c = c + n
f(1) # => 2
g(1) # => UnboundLocalError: local variable 'c' referenced before assignment
Thanks!
谢谢!
回答by Greg Hewgill
Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the global
statement:
在函数内,默认情况下,分配给的变量被视为局部变量。要分配给全局变量,请使用以下global
语句:
def g(n):
global c
c = c + n
This is one of the quirky areas of Python that has never really sat well with me.
这是 Python 的古怪领域之一,我从来没有真正适应过。
回答by ironfroggy
Global state is something to avoid, especially needing to mutate it. Consider if g()
should simply take two parameters or if f()
and g()
need to be methods of a common class with c
an instance attribute
全局状态是需要避免的,尤其是需要对其进行变异。试想,如果g()
要简单地采取两个参数,或者f()
和g()
需要与一个公共类的方法c
的实例属性
class A:
c = 1
def f(self, n):
print self.c + n
def g(self, n):
self.c += n
a = A()
a.f(1)
a.g(1)
a.f(1)
Outputs:
输出:
2
3
回答by Krzysiek Goj
Errata for Greg's post:
Greg 帖子的勘误表:
There should be no before they are referenced. Take a look:
在它们被引用之前应该没有。看一看:
x = 1
def explode():
print x # raises UnboundLocalError here
x = 2
It explodes, even if x is assigned after it's referenced. In Python variable can be local or refer outer scope, and it cannot change in one function.
它会爆炸,即使 x 在它被引用后被赋值。在 Python 中,变量可以是局部的,也可以是引用外部作用域,并且它不能在一个函数中改变。
回答by Krzysiek Goj
Other than what Greg said, in Python 3.0, there will be the nonlocal statement to state "here are some names that are defined in the enclosing scope". Unlike global those names have to be already defined outside the current scope. It will be easy to track down names and variables. Nowadays you can't be sure where "globals something" is exactly defined.
除了 Greg 所说的,在 Python 3.0 中,会有非本地语句来说明“这里有一些在封闭范围内定义的名称”。与 global 不同,这些名称必须已经在当前范围之外定义。追踪名称和变量会很容易。如今,您无法确定“全局某物”的确切定义位置。