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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17641431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:45:50  来源:igfitidea点击:

Python Error: local variable referenced before assignment

pythonvariablescompiler-errors

提问by hh54188

Here is my code:

这是我的代码:

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

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

the error occurred when I add the GLO = temp, if I comment it, the function could be execute successfully, why?

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

How can I set GLO = temp?

我该如何设置GLO = temp

回答by zhangyangyu

Python looks the whole function scope first. So your GLOrefers to the one below, not the global one. And refer the LEGB rule.

Python 首先查看整个函数作用域。所以你GLO指的是下面的那个,而不是全局的。并参考LEGB 规则

GLO = time.time()

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

GLO = Test(GLO)

or

或者

GLO = time.time()

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

Test()

回答by Prahalad Deshpande

Within the Test method specify that you want to refer to the globally declared GLO variable as shown below

在 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

A similar question can be found here : Using a global variable within a method

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