python从字符串调用类实例

时间:2018-10-11 05:30:06

标签: python string class instance

我宣布了一个课程:

class Persons:

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

我创建了一个实例:

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

现在,我想从输入中获取一个字符串,该字符串将告诉我该人的ID,然后将其值从“ 0”切换为“ 1”:

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

所以我想将字符串“ name”更改为相同名称的类实例。我不介意通过名称(p1)或person_id(“ p1”)选择人员。两种方法都不错。

1 个答案:

答案 0 :(得分:2)

只要创建一个人的字典即可

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

inp_string应该是p1


您可以轻松地用一个类包装它:

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>}>