Home > Software design >  How do I print the attributes of a user-specified object?
How do I print the attributes of a user-specified object?

Time:08-02

I would like for the user to input the name of an object and be able to process their choice after it has been entered. This is the idea I had

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)

but obviously the input choose_a_person will remain a string which has no attributes. Is there another method to do this? I don't want to have to run the input through a series of if statements to determine which object to print as I am planning to increase the number of objects in this class.

CodePudding user response:

Store your persons in a dict and then get by a name:

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)

Also, as general advice start your class names with the capital letter.

CodePudding user response:

If, for some reason, the answer given by @funnydman is not applicable to your situation - another solution would be to use the locals function, which returns a dictionary of the local variables. Then you can do something like person = locals().get(choose_a_person]. There's also eval, but it is notoriously unsafe.

  • Related