没有在for循环中定义python全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17645011/
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 global variable not defined in for loop
提问by anthonybell
This code gives the error: UnboundLocalError: local variable 'LINES' referenced before assignment
but LINES
is clearly initialized since if I comment out the line below the print statement it throws no errors and prints len(lines) = 0
as expected. Am I not understanding something about python?? Whats going on here?
这段代码给出了错误:UnboundLocalError: local variable 'LINES' referenced before assignment
但LINES
显然是初始化的,因为如果我注释掉打印语句下面的行,它不会抛出任何错误并按len(lines) = 0
预期打印 。我是不是对 python 不了解?这里发生了什么?
LINES = []
def foo():
for prob in range(1,3):
print "len(lines) = %d" % len(LINES)
LINES = []
if __name__ == "__main__":
foo()
采纳答案by John La Rooy
You can accessglobal variable from inside foo
, but you can't rebind them unless the global
keyword is used
您可以从 inside访问全局变量foo
,但除非使用global
关键字,否则无法重新绑定它们
So you can use LINES.append(...)
or LINES[:] = []
as they are merely modifying the list that LINES references.
因此,您可以使用LINES.append(...)
或LINES[:] = []
因为它们只是修改 LINES 引用的列表。
When you try to assign to LINES
using LINES = []
, Python knows it needs to create an entry for LINES in the functions local variables. Since you are trying to use len(LINES)
before assigning anything to the local variable, it causes an error
当您尝试分配LINES
using 时LINES = []
,Python 知道它需要在函数局部变量中为 LINES 创建一个条目。由于您len(LINES)
在将任何内容分配给局部变量之前尝试使用,因此会导致错误
You can inspect foo
like this
您可以检查foo
这样的
>>> foo.func_code.co_nlocals
2
>>> foo.func_code.co_varnames
('prob', 'LINES')
If you define foo
again without the LINES = []
, you'll see that Python no longer marks it as a local variable.
如果您在foo
没有 的情况下再次定义LINES = []
,您将看到 Python 不再将其标记为局部变量。
回答by jh314
You need to use the global
keyword:
def foo():
global LINES
for prob in range(1,3):
print "len(lines) = %d" % len(LINES)
LINES = []
Otherwise, Python will think that LINES
is local, and printing out the value before setting it to []
will be an issue
否则,Python 会认为这LINES
是本地的,并且在将其设置为之前打印出该值[]
将是一个问题
You can get the value of global variable LINES
by printing it out, but when you have the statement
您可以LINES
通过打印出来获取全局变量的值,但是当您有语句时
LINES = []
which tries to set LINES
to a new list, Python interprets it as a local variable
它试图设置LINES
为一个新列表,Python 将其解释为局部变量
回答by desired login
Python will first look in the function scope for your variable, before it looks in the global (module level) scope. Since you assign to LINES
in your example function, python knows not to use the global variable, but you attempt to access this variable before you define it. You should either initialise LINES
before the print statement, or leave out the LINES = []
statement.
Python 将首先查看变量的函数范围,然后再查看全局(模块级别)范围。由于您LINES
在示例函数中赋值给,python 知道不使用全局变量,但您尝试在定义它之前访问该变量。您应该LINES
在打印语句之前初始化,或者省略该LINES = []
语句。
回答by charmoniumQ
As Desired Login said,
正如 Desired Login 所说,
Since you assign to LINES in your example function, python knows not to use the global variable, but you attempt to access this variable before you define it.
由于您在示例函数中分配给 LINES,python 知道不使用全局变量,但您尝试在定义它之前访问该变量。
This is not the end, you can fix this by using a global keyword, telling python that the LINES
in the function is the same as the LINES
outside of the function.
这还不是结束,您可以通过使用 global 关键字来解决此问题,告诉 pythonLINES
函数内的与LINES
函数外的相同。
Try:
尝试:
LINES = []
def foo():
global lines
for prob in range(1,3):
print "len(lines) = %d" % len(LINES)
LINES = []
if __name__ == "__main__":
foo()