繁体   English   中英

Python 3.6-用户输入调用类变量

[英]Python 3.6 - user input call class variable

我对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?")

从这里开始,我尝试了多种方法让输入字符串(“香蕉”)调用变量(香蕉),然后执行在该类下定义的其他方法。 使用字典键不起作用,因为我想包含多个属性而不是仅包含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'

您仍然应该使用查找字典。 它的值可以是保存每个水果属性的另一个dict,也可以是Fruit对象。

您可以使用类似的方法,这只是草稿来显示方法

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

这是我的:

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的

输出:

What fruit would you like to know about? banana
Here are the attr. of  banana :  name: banana color: yellow price: $3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM