我希望用户输入对象的名称,并能够在输入后处理他们的选择。这就是我的想法
class somebody:
def __init__(self, location, age, sport):
self.location = location
self.age = age
self.sport = sport
nick = somebody('Houston','22','football')
david = somebody('College Station','25','swimming')
peter = somebody('Austin','15','track')
choose_a_person = input('Enter the name of a person: ') #identify which person they are asking about
print('Location is', choose_a_person.location)
print('Age is', choose_a_person.age)
print('Sport is', choose_a_person.sport)
Run Code Online (Sandbox Code Playgroud)
但显然输入的Choose_a_person将仍然是一个没有属性的字符串。还有其他方法可以做到这一点吗?我不想通过一系列 if 语句运行输入来确定要打印哪个对象,因为我计划增加此类中的对象数量。
将您的人员存储在 a 中dict
,然后获取名称:
class Somebody:
def __init__(self, location, age, sport):
self.location = location
self.age = age
self.sport = sport
nick = Somebody('Houston', '22', 'football')
david = Somebody('College Station', '25', 'swimming')
peter = Somebody('Austin', '15', 'track')
persons = {
'nick': nick,
'david': david,
'peter': peter
}
name = input('Enter the name of a person: ') # identify which person they are asking about
choose_a_person = persons[name]
print('Location is', choose_a_person.location)
print('Age is', choose_a_person.age)
print('Sport is', choose_a_person.sport)
Run Code Online (Sandbox Code Playgroud)
另外,作为一般建议,类名以大写字母开头。