简体   繁体   English

Python返回未定义的全局变量

[英]Python returns global variable not defined

I have a method that inside it I scan an excel file in python and in another method I want to check an entry in a list in which I extracted the data from the excel sheet in the first method as follows: 我有一种方法可以在其中扫描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"

An error message is outputted when I type using_from_first_method() 当我输入using_from_first_method()时输出一条错误消息

NameError: global name 'node_positions_ascending_inter' is not defined

Why is it outputted as I already have defined node_positions_ascending_inter to be a global variable? 为什么将其输出,因为我已经将node_positions_ascending_inter定义为全局变量?

You need to declare node_positions_ascending_inter as a global in the using_from_first_method function. 您需要在using_from_first_method函数中将using_from_first_method declare node_positions_ascending_inter为全局变量。 I got the below code (simplification) to run just fine. 我得到了下面的代码(简化),可以正常运行。

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

If you are still having issues maybe the problem lies in the filling of the array. 如果仍然有问题,那么问题可能出在阵列的填充上。 Are you sure the first method is being called and successfully creating the global before the second tries to access it? 您确定在调用第二种方法之前,第一种方法已被调用并成功创建了全局方法吗? Also, see the docs on globals here . 另外,请在此处查看有关globals的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM