我对Python(以及一般的编程)非常陌生,所以如果我提出错误的问题,我会道歉。
我想创建一个工具,用于从用户输入字符串的字典中查找数据,如果字符串与字典中的变量匹配,则打印变量的属性。我找不到将字符串输入转换为预定义变量的方法。以下是我到目前为止的总结:
class Fruit:
def __init__(self, name, color):
self.name = name
self.color = color
banana = Fruit('banana', 'yellow')
fruit_choice = input("What fruit would you like to know about?")
从这里开始,我尝试了多种方法让输入字符串(“banana”)调用变量(banana),然后执行在类下定义的其他方法。使用字典键不起作用,因为我想要包含多个属性而不仅仅是1.
答案 0 :(得分:1)
如果您使用字典,其中键是水果的名称,并且值是您的Fruit
实例,您只需查找值,并覆盖__str__
,无论您想要什么水果描述:
class Fruit:
def __init__(self, name, color):
self.name = name
self.color = color
def __str__(self):
return '{}s are {}'.format(self.name, self.color)
dct = {}
dct['banana'] = Fruit('banana', 'yellow')
现在,您可以使用当前的方法查找水果的属性:
In [20]: ask = input('What fruit would you like to know about? ')
What fruit would you like to know about? banana
In [21]: dct.get(ask, 'Fruit not found')
Out[21]: bananas are yellow
这也将处理字典中没有水果的情况:
In [23]: dct.get('apple', 'Fruit not found')
Out[23]: 'Fruit not found'
答案 1 :(得分:0)
您仍应使用查找字典。它的值可能是另一个包含每个水果属性或水果对象的字典。
答案 2 :(得分:0)
你可以使用类似的东西,这只是一个草稿来展示方法
class Fruit:
def __init__(self, name, color):
self.name = name
self.color = color
def __str__(self):
return "{} : {}".format(self.name, self.color)
fruit_dict = dict()
banana = Fruit('banana', 'yellow')
fruit_dict.update({banana.name : banana})
fruit_choice = input("What fruit would you like to know about?")
user_fruit = fruit_dict.get(fruit_choice)
if user_fruit is not None:
print(user_fruit)
输出(如果输入是香蕉)
banana : yellow
答案 3 :(得分:0)
这是我的:
class Fruit:
def __init__(self, name, color, price):
self.name = name
self.color = color
self.price = price
def __str__(self):
return "name: "+self.name+" color: "+self.color+" price: $"+str(self.price)
dict_of_fruits = {}
banana = Fruit('banana', 'yellow', 3)
apple = Fruit('apple', 'red', 2)
dict_of_fruits[banana.name] = banana
dict_of_fruits[apple.name] = apple
fruit_choice = input("What fruit would you like to know about?")
if fruit_choice in dict_of_fruits:
print("Here are the attr. of ",fruit_choice,': ',dict_of_fruits[fruit_choice])
else:
print("Sorry I could not find ",fruit_choice," in my records")
我添加了__str__()
方法以使打印效果更好,以及新的price
属性,因为您提到有超过2个attr&#39>
输出:
What fruit would you like to know about? banana
Here are the attr. of banana : name: banana color: yellow price: $3