1

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.

1 Answer 1

2

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>}>
Sign up to request clarification or add additional context in comments.

5 Comments

It has to be a Class. That's the restriction.
Python version 3.4 does not support a 'F' prefix
You can upgrade or remove __repr__, they are just for visualization
I'm upgrading. I just need to ajust the code because I simplifed my problem a lot to ask the question here. Shouldn't be too long ...
Most likely you forgot to persons = Persons()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.