Python 错误:赋值前引用局部变量

hh5*_*188 2 python variables compiler-errors

这是我的代码:

import time

GLO = time.time()

def Test():
    print GLO
    temp = time.time();
    print temp
    GLO = temp

Test()
Run Code Online (Sandbox Code Playgroud)

回溯(最近一次调用最后一次):文件“test.py”,第 11 行,在 Test() 文件“test.py”,第 6 行,在测试打印 GLO UnboundLocalError:分配之前引用的局部变量“GLO”

添加时出现错误GLO = temp,如果注释掉,函数就可以成功执行,为什么?

我该如何设置GLO = temp

Pra*_*nde 5

在 Test 方法中指定您要引用全局声明的 GLO 变量,如下所示

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
Run Code Online (Sandbox Code Playgroud)

可以在这里找到类似的问题: 在方法中使用全局变量