簡體   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