首页 > 解决方案 > 使用用户输入获取来自类 python3 的信息

问题描述

我对python相当陌生,我知道我做错了,但似乎找不到必须完成的方法。

我希望用户输入两次他想要的框。我想用他选择的box的值,把它们相互相加,然后打印出来,所以2x input 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())

标签: pythonpython-3.x

解决方案


对此代码的一些建议:

  • 保持类名单数
  • 只有类中的方法可以/应该使用参数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)'。我不确定当没有给定框时您想如何处理这种情况box_name,但是您可以将该return 0行更改get_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

如果您有任何问题,请告诉我。


推荐阅读