0

this is my code:

def search_people():
    search = input("Who do you want to search for: ") 

class people:
    def __init__(self, full_name, birthday, telnum, other):
        self.name = full_name
        self.full_name = full_name
        self.birthday = birthday #ddmmyyyy
        self.telnum = telnum
        self.other = other

Sudar = people("Fullname: Sudaravan Surenthiran", "Birhtday: 10/08/2004", 
"Telephone number: 070 006 04 01",
"Other information: Loves chocolate"

So what i'm trying to do is if the person inputs the person's name for example 'sudar'. It should show the info using:

print(Sudar.name)
print(Sudar.birthday)
print(Sudar.telnum)
print(Sudar.other)

And if i search for other_person It should use:

print(other_person.name)
print(other_person.birthday)
print(other_person.telnum)
print(other_person.other)

I just want to know if there's any way to do this on python 3.6?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Sudar
  • 59
  • 1
  • 2
  • 7
  • 1
    There are definitely ways to do this. However your example shows no signs of work to solve the actual question, and smells like a homework problem you want solved for you. Please post the code of what you have done so far and ask for help where you go stuck. – match Feb 04 '18 at 12:00
  • @match on the post i posted the part of my code. It's the main part. I just can't find a way to do the searched. I tried 'search.name' but it kept saying that a string has no attribut(which is true). I'm stuck in the part where after the user inputs and after confirming the input i'm unable to redirect the user to 'the input'.name. And it's not a homework i do this as a hobby. – Sudar Feb 04 '18 at 14:22
  • Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – OneCricketeer Feb 04 '18 at 16:14

1 Answers1

0

The simplest option is to look at locals() as a dictionary - so you can do:

print(locals()[search].name)

However using locals here is not ideal and if you want this to be properly searchable, it might be clearer to store the class instances in a dictionary, something like the following (replacing ... with actual class params):

peeps = {}
peeps['Sudar'] = people(...)
peeps['Alice'] = people(...)

You can then refer to people instances by doing:

peeps[search].name

(This is technically the same approach as using locals() except you are using a named dictionary rather than picking out variable names, which I would argue is clearer and safer).

match
  • 10,388
  • 3
  • 23
  • 41