简体   繁体   English

全局变量未定义,即使它出现在 globals()

[英]Global variable not defined even though it appears in globals()

I wrote this code:我写了这段代码:

def openFile():
  f = open("test.txt", "r")
  mainInput = f.read()

  global tupleMain
  tupleMain = [tuple(mainInput.split(" ")) for mainInput in mainInput.strip(",").split("\n")]

As you can see, I have defined tupleMain as a global variable, but when I try to use it outside the function, I get:如您所见,我已将 tupleMain 定义为全局变量,但是当我尝试在 function 之外使用它时,我得到:

NameError: name 'tupleMain' is not defined

If I run:如果我运行:

is_global = "tupleMain" in globals()
print(is_global)

The output is: output 是:

True

I just don't get why it says it's not defined if it's in globals() and have set it to global.我只是不明白为什么它说如果它在 globals() 中并已将其设置为全局则未定义。

Thanks in advance提前致谢

EDIT: I use the variable in the following function:编辑:我在以下 function 中使用变量:

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)

You never called the function before using the global variable it declares in some other function, so the code inside the function which declares the variable as global never got executed.在使用它在其他一些 function 中声明的全局变量之前,您从未调用过 function,因此 function 中的代码从未执行过,它将变量声明为global变量。 You need to at-least execute or call the function before referencing the global variable.在引用全局变量之前,您至少需要执行或调用 function。

Either call the function before you use the global variable elsewhere or define the global variable at the module level inside your code.在其他地方使用全局变量之前调用 function 或在代码中的模块级别定义全局变量。

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

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