Domiinic
Domiinic

Reputation: 67

python call class instance from string

I declared a class:

class Persons:

    def __init__(self, person_id, value:
        self.person_id = person_id
        self.value = value

and I created an instance:

p1 = Persons("p1", "0")

Now I want to take a string from an input that will tell me the person's id, and then switch it's value from "0" to "1":

inp_string = input("Which person should have its value changed?")
name = "p" + inp_string
name.value = "1"

So I want to change the string 'name' to the class instance of the same name. I don't mind to select the person by its name (p1) or by it's person_id ("p1"). Either way is good.

Upvotes: 1

Views: 559

Answers (1)

awesoon
awesoon

Reputation: 33661

Just create a dict of persons:

persons_dict = {'p1': Persons("p1", "0")}
inp_string = input("Which person should have its value changed?")
persons_dict[inp_string].value = '1'

inp_string should be p1


You can easily wrap it with a class:

In [32]: class Person:
    ...:     def __init__(self, person_id, value):
    ...:         self.person_id = person_id
    ...:         self.value = value
    ...:     def __repr__(self):
    ...:         return f'Person<person_id: {self.person_id}, value: {self.value}>'
    ...:

In [33]: class Persons:
    ...:     def __init__(self):
    ...:         self.persons = {}
    ...:     def add_person(self, person_id, value):
    ...:         if person_id in self.persons:
    ...:             raise ValueError('person_id already exists')
    ...:         self.persons[person_id] = Person(person_id, value)
    ...:     def get_person_by_id(self, person_id):
    ...:         return self.persons[person_id]
    ...:     def __repr__(self):
    ...:         return f'Persons<{self.persons}>'
    ...:

In [34]: persons = Persons()

In [35]: persons.add_person('p1', '0')

In [36]: persons.add_person('p2', '2')

In [37]: persons
Out[37]: Persons<{'p1': Person<person_id: p1, value: 0>, 'p2': Person<person_id: p2, value: 2>}>

In [38]: persons.get_person_by_id('p1').value = '1'

In [39]: persons
Out[39]: Persons<{'p1': Person<person_id: p1, value: 1>, 'p2': Person<person_id: p2, value: 2>}>

Upvotes: 2

Related Questions