将用户输入转换为变量名(python 2.7)
假设Bob在一个Tkinter的文本输入框里输入了他的名字,'Bob Jones'。之后,我想像这样访问他的名字:
BobJones = {
'name':'Bob Jones',
'pet\'s name':'Fido'
}
我该怎么做才能把Bob输入的内容自动赋值给一个新变量,而不需要手动去写呢?
提前谢谢你。
1 个回答
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
这里你是在定义一个类(可以把它想象成一个模板),这个类是用来表示用户的。然后你会为每一个人创建一个新的用户对象,并把这些对象存储在一个叫做 users
的列表里。