python - 全局变量未定义,即使它出现在 globals()
问题描述
我写了这段代码:
def openFile():
f = open("test.txt", "r")
mainInput = f.read()
global tupleMain
tupleMain = [tuple(mainInput.split(" ")) for mainInput in mainInput.strip(",").split("\n")]
如您所见,我已将 tupleMain 定义为全局变量,但是当我尝试在函数外部使用它时,我得到:
NameError: name 'tupleMain' is not defined
如果我运行:
is_global = "tupleMain" in globals()
print(is_global)
输出是:
True
我只是不明白为什么它说如果它在 globals() 中并已将其设置为全局则未定义。
提前致谢
编辑:我在以下函数中使用变量:
def tableFunction():
fname = [x[2] for x in tupleMain]
sname = [x[3] for x in tupleMain]
position = [x[1] for x in tupleMain]
salary = [x[4] for x in tupleMain]
team = [x[0] for x in tupleMain]
playerTable = PrettyTable()
playerTable.field_names= ["Surname", "First Name", "Salary", "Position", "Team"]
for x in tupleMain:
playerTable.add_row([x[3], x[2], x[4], x[1], x[0]])
print(playerTable)
解决方案
在使用它在其他函数中声明的全局变量之前,您从未调用过该函数,因此函数内声明该变量的代码global
从未被执行。在引用全局变量之前,您至少需要执行或调用该函数。
在其他地方使用全局变量之前调用该函数,或者在代码中的模块级别定义全局变量。
推荐阅读
- javascript - 推送通知删除订阅
- google-sheets - 计算跨越两个不同年份的两个日期之间每个月的天数
- sass - Increment headings and variables using a for loop that apply's font-size in scss
- ruby-on-rails - 不能在葡萄异常上使用 Rails http 状态?
- scala - EMR 上的自定义数据源插件抛出 java.lang.NoClassDefFoundError: scalaj/http/Http
- asynchronous - 如何从同步方法调用异步方法?
- python - 数据框列中的 iteritems()
- javascript - 如何使用 Jquery 触发选项的选择
- javascript - 从 JSON 文件中获取数据到 jQuery 数据表中
- python - TypeError: Empty 'DataFrame': no numeric data to plot, 不确定我的代码有什么问题?