如何通过名称获取对象

时间:2014-07-15 23:02:53

标签: python object

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

如果&#39;水果&#39;对象是全局的,您可以通过

访问它
global()[favorit_fruit].name

如果&#39;水果&#39;是另一个对象的一部分,你只需使用它的命名空间

fruitBowl[favorit_fruit].name

假设:

fruitBowl.plum = Fruit('plum', 'blue')
相关问题