Python用类实现咖啡机
时间: 2023-11-29 22:45:52 浏览: 178
以下是使用Python类实现咖啡机的示例代码:
```python
class CoffeeMachine:
def __init__(self, water, milk, coffee_beans, cups, money):
self.water = water
self.milk = milk
self.coffee_beans = coffee_beans
self.cups = cups
self.money = money
def make_coffee(self, water_needed, milk_needed, beans_needed, cost):
if self.water < water_needed:
print("Sorry, not enough water!")
elif self.milk < milk_needed:
print("Sorry, not enough milk!")
elif self.coffee_beans < beans_needed:
print("Sorry, not enough coffee beans!")
elif self.cups < 1:
print("Sorry, not enough cups!")
else:
print("I have enough resources, making you a coffee!")
self.water -= water_needed
self.milk -= milk_needed
self.coffee_beans -= beans_needed
self.cups -= 1
self.money += cost
def buy(self):
choice = input("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino: ")
if choice == "1":
self.make_coffee(250, 0, 16, 4)
elif choice == "2":
self.make_coffee(350, 75, 20, 7)
elif choice == "3":
self.make_coffee(200, 100, 12, 6)
else:
print("Invalid choice!")
def fill(self):
self.water += int(input("How many ml of water do you want to add? "))
self.milk += int(input("How many ml of milk do you want to add? "))
self.coffee_beans += int(input("How many grams of coffee beans do you want to add? "))
self.cups += int(input("How many disposable cups do you want to add? "))
def take(self):
print("I gave you $", self.money)
self.money = 0
def remaining(self):
print("The coffee machine has:")
print(self.water, "of water")
print(self.milk, "of milk")
print(self.coffee_beans, "of coffee beans")
print(self.cups, "of disposable cups")
print("$", self.money, "of money")
# 创建一个咖啡机对象
my_machine = CoffeeMachine(400, 540, 120, 9, 550)
# 与用户交互
while True:
action = input("What would you like to do? (buy, fill, take, remaining, exit): ")
if action == "buy":
my_machine.buy()
elif action == "fill":
my_machine.fill()
elif action == "take":
my_machine.take()
elif action == "remaining":
my_machine.remaining()
elif action == "exit":
break
else:
print("Invalid action!")
```
该代码创建了一个名为`CoffeeMachine`的类,该类具有制作咖啡、购买咖啡、填充咖啡机、取走咖啡机中的钱和显示咖啡机状态等方法。在类的构造函数中,我们初始化了咖啡机的水、牛奶、咖啡豆、杯子和钱的数量。然后,我们使用一个无限循环与用户交互,直到用户选择退出。
阅读全文