簡體   English   中英

Python返回未定義的全局變量

[英]Python returns global variable not defined

我有一種方法可以在其中掃描python中的excel文件,而在另一種方法中,我要檢查列表中的條目,該列表是在第一種方法中從excel工作表中提取數據的,如下所示:

def first():
    nodes_sh = xlrd.open_workbook(file_location)
    sh_method = nodes_sh.sheet_by_index(0)
    global node_data_inter
    node_data_inter = [[sh_method.cell_value(rr, co) for co in range(sh_method.ncols)] for rr in range(sh_method.nrows)] #O(rows*cols) # A loop to get all the data in the excel sheet of "Nodes Co-ordinates"
    global node_positions_ascending_inter
    node_positions_ascending_inter = dc.deepcopy(node_data_inter) #O(rows*cols)
    for rowss in range(len(node_positions_ascending_inter)): #O(rows)
        del (node_positions_ascending_inter[rowss][0:3])
        del (node_positions_ascending_inter[rowss][2])


def using_from_first_method():
    global node_positions_ascending_inter
    if node_positions_ascending_inter[0][0] == 1.25:
        print "Yes"

當我輸入using_from_first_method()時輸出一條錯誤消息

NameError: global name 'node_positions_ascending_inter' is not defined

為什么將其輸出,因為我已經將node_positions_ascending_inter定義為全局變量?

您需要在using_from_first_method函數中將using_from_first_method declare node_positions_ascending_inter為全局變量。 我得到了下面的代碼(簡化),可以正常運行。

def first():
    global node_positions_ascending_inter
    node_positions_ascending_inter = [1.25, 1.5, 1.3, 1.45]

def using_from_first_method():
    global node_positions_ascending_inter
    if node_positions_ascending_inter[0] == 1.25:
        print("Yes")

first()
using_from_first_method()

如果仍然有問題,那么問題可能出在陣列的填充上。 您確定在調用第二種方法之前,第一種方法已被調用並成功創建了全局方法嗎? 另外,請在此處查看有關globals的文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM