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

时间:2014-04-09 00:20:02

标签: python variables python-2.7 dictionary

让我们说鲍勃输入他的名字,鲍勃琼斯,'进入Tkinter文本输入字段。后来,我希望能够像这样访问他的名字:

BobJones = {
'name':'Bob Jones',
'pet\'s name':'Fido'
}

如何制作,以便将Bob输入的任何内容分配为新变量,而无需手动将其写入?

提前致谢。

1 个答案:

答案 0 :(得分:1)

为了扩展上述评论,我想你想要更像这样的东西:

# 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

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