python错误:在赋值之前引用了局部变量

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 = temp时发生了错误,如果我对它进行注释,函数就可以成功执行,为什么?

如何设置GLO = temp


在测试方法中,指定要引用全局声明的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首先查看整个函数范围。所以你的GLO指的是下面的那个,而不是全球的那个。并参考法律法规。

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()