2013-07-14 2 views
0

Вот мой код: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?

ответ

1

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

В методе испытания указать, что вы хотите, чтобы обратиться к глобально объявленной переменной 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

Смежные вопросы