未在for循环中定义的python全局变量

编程入门 行业动态 更新时间:2024-10-12 03:23:26
本文介绍了未在for循环中定义的python全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

此代码给出错误: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全局变量

本文发布于:2023-06-05 11:08:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/518324.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:定义   全局变量   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!