创建调用方法的类的2个不同实例?

Posted

技术标签:

【中文标题】创建调用方法的类的2个不同实例?【英文标题】:Create 2 different instances of a class that calls methods? 【发布时间】:2022-01-21 06:07:39 【问题描述】:

我设法开发了一个模拟食品外卖订购系统的程序。我创建了Takeout 类及其函数,这些函数成功地接受我自己的输入并打印出我的订单。我的问题是尝试开发调用方法来执行随机人订单代码的类实例(即苏珊的订单为Susan = Takeout(),或罗伯特的订单为Robert = Takeout())。我想包括那些充当演示的实例供观众观看,但我不知道如何去做。

我的编码如下所示(目前按预期工作):

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

这是程序的输出:

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

【问题讨论】:

我不明白你的问题。这里有很多代码,看起来并不相关。你能提供一个简单的例子来说明你想要完成的事情吗? 换句话说,请提供minimal reproducible example。 我很抱歉@juanpa.arrivillaga 没有展示一个清晰的例子,不知道如何包含控制台的输出。我在上面显示的帖子中包含了一个基本示例,其中涉及我从列出的菜单项中输入我自己的订单,其中计算我的订单的总价格并打印订单和价格。我想通过实现类实例而不使用用户输入来执行此操作,但我不确定如何执行此操作。 【参考方案1】:

问题是您的所有方法都在类之外,使它们成为函数,这使您无法将客户的订单保存在您创建的类实例中。

我编辑了您的代码,将这两个列表变成了字典并简化了 if 语句(它不接受除 1 到 15 和“c”之外的任何内容)。它可以进一步优化(或扩展),但我把它留给你:

注意 - 在 Ubuntu 20.04 上测试,使用 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()

输出:

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!

【讨论】:

以上是关于创建调用方法的类的2个不同实例?的主要内容,如果未能解决你的问题,请参考以下文章

Python中的类和方法使用举例

使用从测试方法调用的方法的类的 OCMock

JAVA类的方法调用

django-基于类的视图

如何为类的每个实例创建实例特定的方法?

反射生成对象,调用对象方法