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

2024-04-20 04:59:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写一个程序从数据库中提取一个部门列表。我想避免硬编码,因为列表可能会改变。你知道吗

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

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

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

Tags: 函数程序数据库列表defvarsglobal部门
2条回答

不要在这里使用动态变量。毫无意义,只使用Python的一个内置容器,比如dict。你知道吗

但是,代码无法工作的原因是vars()在没有参数的情况下调用时返回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.

实际上,您只需要使用dict返回的globals()对象。但是这会让你想知道,为什么不把全局名称空间放在外面,而是使用你自己的定制dict对象呢?阅读this相关问题。你知道吗

谢谢你的小费。我能用字典写我需要的代码。作为python的新手,它需要一些尝试和错误,但是解决方案比我最初尝试的要好。你知道吗

谢谢你的帮助!你知道吗

相关问题 更多 >