从列表创建变量并全局访问

Creating variables from list and accessing globally

我正在编写一个从数据库中提取部门列表的程序。我想避免对此进行硬编码,因为列表可能会更改。

我想为每个部门创建一个变量以将问题填充到 GUI 中。我遇到的问题是我可以使用 vars() 函数从数据库列表中创建变量。然后我存储变量名称列表,以便我可以在我的程序的其他地方引用它们。只要我在同一个 def 中做所有事情,就没有问题。但是我不知道如何在单独的函数中引用动态创建的变量。

因为我不会提前知道变量名,所以我不知道如何让它们在其他函数中可用。

deptList = ['deptartment 1', 'deptartment 2', 'deptartment 3', 'deptartment 4', 'deptartment4']

varList=[]

def createVariables():
    global varList    
    for i in range(len(deptList)):

        templst=deptList[i].replace(' ', '')
        varList.append(templst+'Questions')
        globals()['{}'.format(varList[i])] = []


def addInfo():
    global varList

    print('varlist',vars()[varList[1]]) #Keyerror



createVariables()
print(varList)
vars()[varList[1]].append('This is the new question')
print('varlist',vars()[varList[1]]) #Prints successfully

addInfo()

不要在此处使用动态变量。这没有任何意义,只需使用 Python 的内置容器之一,例如 dict

但是,您的代码无法正常工作的原因是 vars() returns locals() 在不带参数的情况下调用。来自 docs:

vars([object]) Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

...

Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

实际上,您只想使用 globals() 返回的 dict 对象。但这应该让你想知道,为什么不把全局名称 -space 去掉,而是使用你自己的自定义 dict 对象?阅读 this 相关问题。

感谢您的提示。我能够用字典编写我需要的代码。作为 python 的新手,它经过了一些反复试验,但解决方案比我最初尝试做的要好。

感谢您的帮助!