【发布时间】:2018-01-08 06:43:13
【问题描述】:
我正在编写一个从数据库中提取部门列表的程序。我想避免硬编码,因为列表可能会改变。
我想为每个部门创建一个变量以将问题填充到 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()
【问题讨论】:
-
您的问题似乎模棱两可。您能否更清楚地说明什么是确定的,什么是不确定的?
-
globals()只返回一个字典。你不能为此创建一个自定义字典吗?为什么需要动态生成全局变量?为什么vars()从数据库返回变量?必须有一种单独的方式从数据库中获取变量名称和值。 -
字典可能足以满足您的用例。
-
在这里使用动态创建的全局变量似乎是不可取的。只需使用
dict对象。不需要varsList