未在for循环中定义的python全局变量 [英] python global variable not defined in for loop
问题描述
此代码给出错误:UnboundLocalError: local variable 'LINES' referenced before assignment
但LINES
显然已初始化,因为如果我注释掉print语句下方的行,它不会引发任何错误并按预期方式打印len(lines) = 0
.我不了解有关python的一些信息吗?这是怎么回事?
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?
LINES = []
def foo():
for prob in range(1,3):
print "len(lines) = %d" % len(LINES)
LINES = []
if __name__ == "__main__":
foo()
推荐答案
您可以从foo
内部访问访问全局变量,但是除非使用global
关键字,否则无法重新绑定它们
You can access global variable from inside foo
, but you can't rebind them unless the global
keyword is used
因此,您可以使用LINES.append(...)
或LINES[:] = []
,因为它们只是修改LINES引用的列表.
So you can use LINES.append(...)
or LINES[:] = []
as they are merely modifying the list that LINES references.
当您尝试使用LINES = []
分配给LINES
时,Python知道它需要在函数局部变量中为LINES创建一个条目.由于您尝试在将任何内容分配给局部变量之前使用len(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
您可以像这样检查foo
>>> foo.func_code.co_nlocals
2
>>> foo.func_code.co_varnames
('prob', 'LINES')
如果再次定义foo
而没有LINES = []
,则会看到Python不再将其标记为局部变量.
If you define foo
again without the LINES = []
, you'll see that Python no longer marks it as a local variable.
这篇关于未在for循环中定义的python全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!