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

问题描述:

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

I’m writing a program that pulls a list of departments from a database. I want to avoid hardcoding this since the list may change.

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

I want to create a variable for each department to populate questions into a GUI. The problem I have is that I can create variables from the database list using the vars() function. I’m then storing the list of variable names so I can reference them elsewhere in my program. As long as I do everything in the same def, there is no problem. But I don’t know how to reference the dynamically created variables in a separate function.

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

Since I won’t know the variable names ahead of time, I don’t know how to make them available in other functions.

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.

Do not use dynamic variables here. It makes no sense, just use one of Python's built-in containers, like a dict.

但是,您的代码不起作用的原因是 vars() 在不带参数调用时返回 locals().来自文档:

But, the reason your code isn't working is because vars() returns locals() when called with no argument. From the docs:

vars([object]) 返回模块、类的 __dict__ 属性,实例,或具有 __dict__ 属性的任何其他对象.

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

...

没有参数,vars() 的作用就像 locals().注意,当地人字典仅对读取有用,因为更新到本地字典被忽略.

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 对象.但这应该让你想知道,为什么不把全局命名空间排除在外,而是使用你自己的自定义 dict 对象?阅读这个相关问题.

So really, you just want to use the dict object returned by globals(). But this should make you wonder, why not just leave the global name-space out of it, and rather, just use your own custom dict object? Read this related question.