请编写一段使用面向对象的编程方式,实现自动贩卖机的程序。
时间: 2024-06-02 10:14:23 浏览: 153
class VendingMachine:
def __init__(self):
self.balance = 0
self.drinks = {"Coke": 2, "Sprite": 2.5, "Water": 1.5}
def insert_coin(self, amount):
self.balance += amount
def get_balance(self):
return self.balance
def buy_drink(self, drink):
if drink not in self.drinks:
return "Invalid drink selection"
price = self.drinks[drink]
if self.balance < price:
return "Insufficient balance"
self.balance -= price
return drink + " is dispensed. Thank you for your purchase!"
# Example usage
vm = VendingMachine()
vm.insert_coin(2)
print(vm.get_balance()) # Output: 2
print(vm.buy_drink("Coke")) # Output: Coke is dispensed. Thank you for your purchase!
阅读全文