让我们定义类和类的三个实例
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
一种方法是维护所创建对象的字典。像这样:
当你得到用户输入时,你引用dict并得到对象。你知道吗
如果“水果”对象是全局对象,则可以通过
如果'fruit'是另一个对象的一部分,只需使用它的名称空间即可
假设:
相关问题 更多 >
编程相关推荐