简体   繁体   中英

using user input for information from classes python3

I'm fairly new to python and I know I am doing it wrong but can't seem to find the way it has to be done.

I want the user to input twice which box he wants. I want to use the value of the boxes he chose and add them to each other, and then print the value, so 2x input box1 should give the value of 80.

Later on I want the possibility to use a lot more boxes.

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())

A couple suggestions for this code:

  • keep class names singular
  • only methods within a class can/should use the argument self as self refers to the instance of the class on which the method was called
  • if you want to check if a Boxes instance exists, you need to keep all Boxes in a list somewhere
  • be a bit more explicit with naming variables and passing them around
  • the input function accepts a prompt string as an argument, which makes things a bit cleaner than having a separate print statement

Here is a refactor:

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'

When run, the above code will continue to ask for new boxes by name and add the specified box's weight to the total until the uses enters anything but 'y' when asked 'Add another? (y/n)' 'Add another? (y/n)' . I'm not sure how you want to handle the case when there is no box with the given box_name , but you can just change that return 0 line in get_box_weight_if_box_exists to be pretty much anything else.

Here's some sample output:

> 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

Let me know if you have questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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