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

2024-05-15 01:34:41 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码:

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


Tags: 代码inpytestimportmosttimedef
2条回答

在测试方法中指定要引用全局声明的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

类似的问题可以在这里找到: Using a global variable within a method

Python首先查看整个函数范围。所以你的GLO指的是下面的那个,而不是全局的。并引用LEGB rule

GLO = time.time()

def Test(glo):
    print glo
    temp = time.time();
    print temp
    return temp

GLO = Test(GLO)

或者

GLO = time.time()

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

Test()

相关问题 更多 >

    热门问题