Python返回未定义的全局变量

时间:2015-07-04 15:39:20

标签: python python-2.7 variables global

我有一个方法在其中我在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定义为全局变量?

1 个答案:

答案 0 :(得分:0)

您需要declare node_positions_ascending_inter作为using_from_first_method函数的全局。我得到了下面的代码(简化),运行得很好。

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

如果您仍然遇到问题,可能问题在于填充阵列。您确定在第二个尝试访问它之前调用第一个方法并成功创建全局吗?另外,请参阅全局here上的文档。

相关问题