简体   繁体   中英

Create 2 different instances of a class that calls methods?

I managed to develop a program that simulates a food takeout ordering system. I've created the class Takeout and its functions that successfully takes my own input and prints out my order. My problem is trying to develop class instances that call the methods to perform the code for a random person's order (ie Susan's order as Susan = Takeout() , or Robert's order as Robert = Takeout() ). I want to include those instances that act as demos for the audience to see but I'm not sure how to go about it.

My coding is shown below (works as intended so far):

Menu = ["fries", "Shack Burger", "Smoke Shack", "Chicken Shack", "Avocado Bacon Burger", "hamburger", "cheeseburger",
        "hotdog", "chicken bites", "cookie", "apple cider", "soda", "milkshake", "iced tea", "water"]  # Here, this
# identifies the food and drinks that the user can order for takeout.

# This lists the prices for each food and drink.
costs = [3.59, 6.89, 8.59, 8.19, 9.29, 6.39, 6.79, 4.49, 5.59, 6.59, 4.09, 3.29, 6.09, 3.29, 3.19]


class Takeout(object):
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def getprice(self):
        return self.price

    def __str__(self):
        return self.name + ' : $' + str(self.getprice())

def buildmenu(Menu, costs): # Defining a function for building a Menu which generates list of food and drinks
    menu = []
    for i in range(len(Menu)):
        menu.append(Takeout(Menu[i], costs[i]))
    return menu

total_price = 0
current_order = []
current_price = []

def get_order():
    global total_price
    while True:
        print("\nWelcome to Shake Shack! What can I get for you? ")
        order = input()
        if order == "1":
            current_order.append(Menu[0])
            current_price.append(costs[0])
            total_price = total_price + (costs[0])
            print(Menu[0] + " - " "$", costs[0])
        elif order == "2":
            current_order.append(Menu[1])
            current_price.append(costs[1])
            total_price = total_price + (costs[1])
            print(Menu[1] + " - " "$", costs[1])
        elif order == "3":
            current_order.append(Menu[2])
            current_price.append(costs[2])
            total_price = total_price + (costs[2])
            print(Menu[2] + " - " "$", costs[2])
        elif order == "4":
            current_order.append(Menu[3])
            current_price.append(costs[3])
            total_price = total_price + (costs[3])
            print(Menu[3] + " - " "$", costs[3])
        elif order == "5":
            current_order.append(Menu[4])
            current_price.append(costs[4])
            total_price = total_price + (costs[4])
            print(Menu[4] + " - " "$", costs[4])
        elif order == "6":
            current_order.append(Menu[5])
            current_price.append(costs[5])
            total_price = total_price + (costs[5])
            print(Menu[5] + " - " "$", costs[5])
        elif order == "7":
            current_order.append(Menu[6])
            current_price.append(costs[6])
            total_price = total_price + (costs[6])
            print(Menu[6] + " - " "$", costs[6])
        elif order == "8":
            current_order.append(Menu[7])
            current_price.append(costs[7])
            total_price = total_price + (costs[7])
            print(Menu[7] + " - " "$", costs[7])
        elif order == "9":
            current_order.append(Menu[8])
            current_price.append(costs[8])
            total_price = total_price + (costs[8])
            print(Menu[8] + " - " "$", costs[8])
        elif order == "10":
            current_order.append(Menu[9])
            current_price.append(costs[9])
            total_price = total_price + (costs[9])
            print(Menu[9] + " - " "$", costs[9])
        elif order == "11":
            current_order.append(Menu[10])
            current_price.append(costs[10])
            total_price = total_price + (costs[10])
            print(Menu[10] + " - " "$", costs[10])
        elif order == "12":
            current_order.append(Menu[11])
            current_price.append(costs[11])
            total_price = total_price + (costs[11])
            print(Menu[11] + " - " "$", costs[11])
        elif order == "13":
            current_order.append(Menu[12])
            current_price.append(costs[12])
            total_price = total_price + (costs[12])
            print(Menu[12] + " - " "$", costs[12])
        elif order == "14":
            current_order.append(Menu[13])
            current_price.append(costs[13])
            counter = counter + 1
            total_price = total_price + (costs[13])
            print(Menu[13] + " - " "$", costs[13])
        elif order == "15":
            current_order.append(Menu[14])
            current_price.append(costs[14])
            total_price = total_price + (costs[14])
            print(Menu[14] + " - " "$", costs[14])
        else:
            print("Sorry, we don't serve that here.\n")
            continue
        if is_order_complete():
            return current_order, total_price

def is_order_complete():
    print("Done! Anything else you would like to order? (Say 'yes' or 'no')")
    choice = input()
    if choice == "no":
        return True
    elif choice == "yes":
        return False
    else:
        raise Exception("Sorry. That is an invalid input.")

def output_order(counter, total_price):
    print("\nOkay, so just to be sure, you want to order: ")
    print("---------------------")
    print(current_order)
    print("---------------------")
    print("Your order will cost $", str(total_price), "for today.")

MyFood = buildmenu(Menu, costs) # Here, we build the Takeout menu for the user.

print("\nWelcome to Shake Shack! Please review our menu before ordering, as you can only order each item *once*!\n")
n = 1
for el in MyFood:
    print(n, '. ', el)
    n = n + 1

def main():
    order = get_order()
    output_order(order, total_price)
    print("\nThank you for your order! Please proceed to the next window for payment. Your order will be ready at the "
          "3rd window. Have a nice day!")

if __name__ == "__main__":
    main()

And this is the output that results from the program:

Welcome to Shake Shack! Please review our menu before ordering, as you can only order each item *once*!

1 .  fries : $3.59
2 .  Shack Burger : $6.89
3 .  Smoke Shack : $8.59
4 .  Chicken Shack : $8.19
5 .  Avocado Bacon Burger : $9.29
6 .  hamburger : $6.39
7 .  cheeseburger : $6.79
8 .  hotdog : $4.49
9 .  chicken bites : $5.59
10 .  cookie : $6.59
11 .  apple cider : $4.09
12 .  soda : $3.29
13 .  milkshake : $6.09
14 .  iced tea : $3.29
15 .  water : $3.19

Welcome to Shake Shack! What can I get for you? 
1
fries - $ 3.59
Done! Anything else you would like to order? (Say 'yes' or 'no')
yes

Welcome to Shake Shack! What can I get for you? 
4
Chicken Shack - $ 8.19
Done! Anything else you would like to order? (Say 'yes' or 'no')
yes

Welcome to Shake Shack! What can I get for you? 
2
Shack Burger - $ 6.89
Done! Anything else you would like to order? (Say 'yes' or 'no')
yes

Welcome to Shake Shack! What can I get for you? 
11
apple cider - $ 4.09
Done! Anything else you would like to order? (Say 'yes' or 'no')
yes

Welcome to Shake Shack! What can I get for you? 
15
water - $ 3.19
Done! Anything else you would like to order? (Say 'yes' or 'no')
no

Okay, so just to be sure, you want to order: 
---------------------
['fries', 'Chicken Shack', 'Shack Burger', 'apple cider', 'water']
---------------------
Your order will cost $ 25.95 for today.

Thank you for your order! Please proceed to the next window for payment. Your order will be ready at the 3rd window. Have a nice day!

Process finished with exit code 0

The problem is that all of your methods are outside the class, making them functions, which keeps you from saving the customer's order within the class instance you created.

I edited your code, making the two lists into a dictionary and simplifying the if statements (it will not accept anything except 1 through 15, and "c"). It can be optimized (or expanded) further, but I leave that to you:

NOTE - Tested on Ubuntu 20.04, using Python 3.8

class Takeout(object):
    menu = {"fries": 3.59, "Shack Burger": 6.89, "Smoke Shack": 8.59, "Chicken Shack": 8.19,
            "Avocado Bacon Burger": 9.29, "hamburger": 6.39, "cheeseburger": 6.79,
            "hotdog": 4.49, "chicken bites": 5.59, "cookie": 6.59,
            "apple cider": 4.09, "soda": 3.29, "milkshake": 6.09,
            "iced tea": 3.29, "water": 3.19, }

    customer_name = ""
    total_price = 0.0
    items_ordered = {}

    def __init__(self, customer_name):
        self.customer_name = customer_name
        # Clear values before each instance
        self.total_price = 0.0
        self.items_ordered = {}
        print(f"\nWelcome to Shake Shack, {customer_name}! " +
              "Please review our menu before ordering:\n")
        for i, (key, value) in enumerate(self.menu.items()):
            print(f"{i + 1}. {key}: ${value:.2f}")

    def get_order(self):
        print("\nWhat can I get for you?")
        while True:
            print("\nEnter a menu item number or 'c' to complete your order: ", end="")
            choice = input()
            if choice.lower() == "c":
                break
            # Ensure choice can be converted to a digit,
            # and that it is between 1 and 15
            elif choice.isdigit() and (0 < int(choice) <= len(self.menu)):
                # Convert the menu into a list
                menu_list = list(self.menu.items())
                # Rebase choice from 1-15 to 0-14
                c = int(choice) - 1
                # Get the chosen dict obj from the menu list (using its index)
                # and append it to the order dict
                self.items_ordered.update({menu_list[c]})
                # Add the price of the item to the total price
                self.total_price += menu_list[c][1]
                print(f"You ordered a {menu_list[c][0]} for ${menu_list[c][1]:.2f}.\n" +
                      f"Your current total is ${self.total_price:.2f}.")
            else:
                print("That is not a valid choice!")
        print(f"Thank you, {self.customer_name}!\n")

def main():
    # First, create an instance for each order
    susan_order = Takeout("Susan")
    susan_order.get_order()

    print("Next order!\n")

    robert_order = Takeout("Robert")
    robert_order.get_order()

    # To make things easy, add them to a list
    orders = [susan_order, robert_order, ]

    # Now you can reference each instance of an order
    for c in orders:
        print(f"{c.customer_name}, your order was:")
        for key, value in c.items_ordered.items():
            print(f"{key}: ${value:.2f}")
        print(f"Your total price was ${c.total_price:.2f}.")
        print("Thank you for your order!\n")


if __name__ == "__main__":
    main()

Output:

Welcome to Shake Shack, Susan! Please review our menu before ordering:

1. fries: $3.59
2. Shack Burger: $6.89
3. Smoke Shack: $8.59
4. Chicken Shack: $8.19
5. Avocado Bacon Burger: $9.29
6. hamburger: $6.39
7. cheeseburger: $6.79
8. hotdog: $4.49
9. chicken bites: $5.59
10. cookie: $6.59
11. apple cider: $4.09
12. soda: $3.29
13. milkshake: $6.09
14. iced tea: $3.29
15. water: $3.19

What can I get for you?

Enter a menu item number or 'c' to complete your order: 1
You ordered a fries for $3.59.
Your current total is $3.59.

Enter a menu item number or 'c' to complete your order: 21
That is not a valid choice!

Enter a menu item number or 'c' to complete your order: 2
You ordered a Shack Burger for $6.89.
Your current total is $10.48.

Enter a menu item number or 'c' to complete your order: quit
That is not a valid choice!

Enter a menu item number or 'c' to complete your order: c
Thank you, Susan!

Next order!


Welcome to Shake Shack, Robert! Please review our menu before ordering:

1. fries: $3.59
2. Shack Burger: $6.89
3. Smoke Shack: $8.59
4. Chicken Shack: $8.19
5. Avocado Bacon Burger: $9.29
6. hamburger: $6.39
7. cheeseburger: $6.79
8. hotdog: $4.49
9. chicken bites: $5.59
10. cookie: $6.59
11. apple cider: $4.09
12. soda: $3.29
13. milkshake: $6.09
14. iced tea: $3.29
15. water: $3.19

What can I get for you?

Enter a menu item number or 'c' to complete your order: 3
You ordered a Smoke Shack for $8.59.
Your current total is $8.59.

Enter a menu item number or 'c' to complete your order: 4
You ordered a Chicken Shack for $8.19.
Your current total is $16.78.

Enter a menu item number or 'c' to complete your order: c
Thank you, Robert!

Susan, your order was:
fries: $3.59
Shack Burger: $6.89
Your total price was $10.48.
Thank you for your order!

Robert, your order was:
Smoke Shack: $8.59
Chicken Shack: $8.19
Your total price was $16.78.
Thank you for your order!

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