Home > Back-end >  How to call object of class by input?
How to call object of class by input?

Time:05-31

I am generating a class of persons and want to get information about a certain person by input. I would like to use the str funtction because I am trying to understand it better. My Idea goes as follows:

class Person:
   __init__(self, f_name, l_name):
       self.f_name = f_name
       self.l_name = l_name

   __str__(self):
      return "The persons full name is:"   f_name   l_name

person1 = Person(Peter, Punk)
person2 = Person(Mia, Munch)

person = input("What persons full name would you like to know?")

print(person) #I am aware that this just fills in the string saved in person, but how do I connect it to the variable?

another idea was to do it as follows:

#class stays the same except:

__init__(self, f_name, l_name):
       self.f_name = f_name
       self.l_name = l_name
       list.append(self)

#and then for the main:

list = []
person1 = Person(Peter, Punk)
person2 = Person(Mia, Munch)

person = input("What persons full name would you like to know?")
    index = list(person)
    print(list[index])

Thankful for any edvice since I am obviously new to Python :D

CodePudding user response:

I think OP has some concept problems here which this answer may go some way to help with.

Start by building a robust class definition. Simple in this case as there are just 2 attributes. Note the use of setters, getters and str, repr and eq dunder overrides.

A small function that checks if a given Person can be found in a list of Persons and reports accordingly.

Create a list with 2 different Person instances

Create another Person that is known not to match anything already in the list.

Run check()

Modify the 'standalone' Person to make it equivalent to something previously constructed.

Run check()

class Person:
    def __init__(self, forename, surname):
        self._forename = forename
        self._surname = surname
    @property
    def forename(self):
        return self._forename
    @forename.setter
    def forename(self, forename):
        self._forename = forename
    @property
    def surname(self):
        return self._surname
    @surname.setter
    def surname(self, surname):
        self._surname = surname
    def __str__(self):
        return f'{self.forename} {self.surname}'
    def __repr__(self):
        return f'{self.forename=} {self.surname=}'
    def __eq__(self, other):
        if isinstance(other, type(self)):
            return self.forename == other.forename and self.surname == other.surname
        return False

def check(list_, p):
    if p in list_:
        print(f'Found {p}')
    else:
        print(f'Could not find {p}')

plist = [Person('Pete', 'Piper'), Person('Joe', 'Jones')]

person = Person('Pete', 'Jones')

check(plist, person)

person.surname = 'Piper'

check(plist, person)

Output:

Could not find Pete Jones
Found Pete Piper

CodePudding user response:

You probably want a mapping between a name and an object. This is what Python's dict dictionary structure is for:

people = {}  # an empty dictionary

people[f'{person1.f_name} {person1.l_name}'] = person1
people[f'{person2.f_name} {person2.l_name}'] = person2

This is creating a string of the first and last name.

You can then lookup the Person object using the full name:

print(people['Peter Punk'])

CodePudding user response:

You could do this with list comprehension like so (also allowing multiple people to have the same first name)

class Person:
   __init__(self, f_name, l_name):
       self.f_name = f_name
       self.l_name = l_name

   __str__(self):
      return "The persons full name is:"   f_name   l_name

personList= []
personList.append(Person(Peter, Punk))
personList.append(Person(Mia, Munch))
personName = input("What persons full name would you like to know?")

print([str(person) for person in personList if person.f_name == personName])
  • Related