簡體   English   中英

使用用戶輸入獲取來自類 python3 的信息

[英]using user input for information from classes python3

我對python相當陌生,我知道我做錯了,但似乎無法找到必須完成的方式。

我希望用戶輸入兩次他想要的框。 我想用他選擇的box的值,把它們相加,然后打印值,所以2x輸入box1應該給出80的值。

后來我希望有可能使用更多的盒子。

class Boxes:
      'boxes with assigned weight'

      def __init__(self, boxnr, weight):
          self.boxnr = boxnr
          self.weight = weight

  box1 = Boxes('box1', 40)
  box2 = Boxes('box2', 70)
  box3 = Boxes('box3', 110)

  def tot_weight(self, weight):
      if input in Boxes:
          total += Boxes[weight.self]
  return self.tot_weight

  print ('which box?')
  weight = input ()

  print('what is your next box?')
  weight = input ()

  print (tot_weight.self.weight())

對此代碼的一些建議:

  • 保持類名單數
  • 只有類中的方法可以/應該使用參數self作為self指代調用該方法的類的實例
  • 如果要檢查Boxes實例是否存在,則需要將所有Boxes保留在某個列表中
  • 命名變量並傳遞它們更明確一點
  • input函數接受一個prompt字符串作為參數,這比單獨的print語句更簡潔

這是一個重構:

class Box:
    '''Box with assigned weight'''
    def __init__(self, name, weight):
        self.name = name
        self.weight = weight

boxes = [
    Box('box1', 40),
    Box('box2', 70),
    Box('box3', 110)
]

def get_box_weight_if_box_exists(box_name, boxes):
    for box in boxes:
        if box.name == box_name:
            return box.weight
    return 0


keep_adding = True
total = 0

while keep_adding:
    box_name = input('Enter a box name: ')
    total += get_box_weight_if_box_exists(box_name, boxes)
    print('Total: {}'.format(total))
    keep_adding = input('Add another? (y/n): ') == 'y'

在運行時,上面的代碼將繼續名字索要新的盒子和指定的盒子的重量加總,直到用途進入什么,但'y'當被問及'Add another? (y/n)' 'Add another? (y/n)' . 當沒有給定box_name框時,我不確定您想如何處理這種情況,但是您可以將get_box_weight_if_box_exists中的return 0get_box_weight_if_box_exists為幾乎任何其他內容。

這是一些示例輸出:

> Enter a box name: box1
Total: 40
> Add another? (y/n): y
> Enter a box name: box2
Total: 110
> Add another? (y/n): y
> Enter a box name: nice
Total: 110
> Add another? (y/n): n

如果您有任何疑問,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM