将用户输入转换为变量名(python 2.7)

将用户输入转换为变量名(python 2.7),python,variables,python-2.7,dictionary,Python,Variables,Python 2.7,Dictionary,假设Bob在Tkinter文本输入字段中输入他的名字“Bob Jones”。稍后,我希望能够像这样访问他的名字: BobJones = { 'name':'Bob Jones', 'pet\'s name':'Fido' } # Define the user class - what data do we store about users: class User(object): def __init__(self, user_name, first_pet):

假设Bob在Tkinter文本输入字段中输入他的名字“Bob Jones”。稍后,我希望能够像这样访问他的名字:

BobJones = {
'name':'Bob Jones',
'pet\'s name':'Fido'
}
# Define the user class - what data do we store about users:

class User(object):
    def __init__(self, user_name, first_pet):
        self.user_name = user_name
        self.first_pet = first_pet

# Now gather the actual list of users

users = []
while someCondition:
    user_name, first_pet = getUserDetails()
    users.append(User(user_name, first_pet))

# Now we can use it

print "The first users name is:"
print users[0].user_name
我如何使它成为一个新的变量,而无需手动写入它,我就可以将Bob输入的任何内容指定为一个新的变量


提前感谢。

要进一步阐述上述评论,我想您可能需要以下内容:

BobJones = {
'name':'Bob Jones',
'pet\'s name':'Fido'
}
# Define the user class - what data do we store about users:

class User(object):
    def __init__(self, user_name, first_pet):
        self.user_name = user_name
        self.first_pet = first_pet

# Now gather the actual list of users

users = []
while someCondition:
    user_name, first_pet = getUserDetails()
    users.append(User(user_name, first_pet))

# Now we can use it

print "The first users name is:"
print users[0].user_name

因此,您正在为用户定义类(将其视为模板),然后创建新的用户对象,每个人一个,并将它们存储在
Users
列表中。

@roippi这没有真正的帮助,因此在编写程序时,您将有一些名称未知的变量,一旦他们被创造出来,就没有别的办法找到他们的名字了?这怎么可能是个好主意呢?你在找一本字典。@ScottHunter那么你是如何创造“新用户”的呢?我对这个很陌生:/哇,真不敢相信我忘了上课!非常感谢,曼诺,没问题。如果您想要的是比这个更轻的东西(并且数据永远不会被更改为“不可变”),您可以使用命名元组而不是类,例如,不,我肯定需要使用类。我为每个用户存储了约50个数据点。