Python Error: local variable referenced before assignment
这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 | import time GLO = time.time() def Test(): print GLO temp = time.time(); print temp GLO = temp Test() |
Traceback (most recent call last): File"test.py", line 11, in
Test() File"test.py", line 6, in Test
print GLO UnboundLocalError: local variable 'GLO' referenced before assignment
当我添加
如何设置
在测试方法中,指定要引用全局声明的glo变量,如下所示
1 2 3 4 5 6 | def Test(): global GLO #tell python that you are refering to the global variable GLO declared earlier. print GLO temp = time.time(); print temp GLO = temp |
这里也有类似的问题:在方法中使用全局变量
python首先查看整个函数范围。所以你的
1 2 3 4 5 6 7 8 9 | GLO = time.time() def Test(glo): print glo temp = time.time(); print temp return temp GLO = Test(GLO) |
或
1 2 3 4 5 6 7 8 9 10 | GLO = time.time() def Test(): global GLO print GLO temp = time.time(); print temp GLO = temp Test() |