如何通过nam获取对象

2024-04-28 07:29:21 发布

您现在位置:Python中文网/ 问答频道 /正文

让我们定义类和类的三个实例

class Fruit():
    def __init__(self, name, color):
        self.name = name
        self.color = color

apple = Fruit('apple', 'red')
plum = Fruit('plum ', 'blue')
apricot = Fruit('apricot', 'orange')

现在用户输入水果名

user_input_fruit = sys.stdin.read() # user typing 'plum'

此时,我有一个值为“plum”的字符串变量。 现在我想得到一个对象,与用户输入相关,比如

favorit_fruit = user_input_fruit

让它变成

>>>print type(favorit_fruit)
<type 'instance'>
>>>print favorit_fruit.name
plum

我怎么能做到?你知道吗

更新

解决方案

class Fruit():
    _dic = {}

    def __init__(self, name, color):
        self._dic[name] = self
        self.name = name
        self.color = color

apple = Fruit('apple', 'red')
plum = Fruit('plum', 'blue')
apricot = Fruit('apricot', 'orange')

fruit_string = 'plum'

favorit_fruit = Fruit._dic[fruit_string]

>>>print type(favorit_fruit)
<type 'instance'>
>>>print favorit_fruit.name
plum

Tags: nameselfappledeftypeclasscolorprint
2条回答

一种方法是维护所创建对象的字典。像这样:

obj_dict = {}
apple = Fruit('apple', 'red')
obj_dict['apple'] = apple
plum = Fruit('plum ', 'blue')
obj_dict['plum'] = plum
apricot = Fruit('apricot', 'orange')
obj_dict['apricot'] = apricot

当你得到用户输入时,你引用dict并得到对象。你知道吗

>>>print type(obj_dict[favorit_fruit])
<type 'instance'>
>>>print obj_dict[favorit_fruit].name
plum

如果“水果”对象是全局对象,则可以通过

global()[favorit_fruit].name

如果'fruit'是另一个对象的一部分,只需使用它的名称空间即可

fruitBowl[favorit_fruit].name

假设:

fruitBowl.plum = Fruit('plum', 'blue')

相关问题 更多 >