上述问题输入输出为>>> v = VendingMachine('candy', 10) >>> v.vend() 'Machine is out of stock.' >>> v.add_funds(15) 'Machine is out of stock. Here is your $15.' >>> v.restock(2) 'Current candy stock: 2' >>> v.vend() 'You must add $10 more funds.' >>> v.add_funds(7) 'Current balance: $7' >>> v.vend() 'You must add $3 more funds.' >>> v.add_funds(5) 'Current balance: $12' >>> v.vend() 'Here is your candy and $2 change.' >>> v.add_funds(10) 'Current balance: $10' >>> v.vend() 'Here is your candy.' >>> v.add_funds(15) 'Machine is out of stock. Here is your $15.' >>> w = VendingMachine('soda', 2) >>> w.restock(3) 'Current soda stock: 3' >>> w.restock(3) 'Current soda stock: 6' >>> w.add_funds(2) 'Current balance: $2' >>> w.vend() 'Here is your soda.'
时间: 2024-03-03 15:50:58 浏览: 16
这是一个关于 VendingMachine 类的问题,以下是实现该类的代码,以满足所需的输入输出:
```python
class VendingMachine:
def __init__(self, product_name, price):
self.product_name = product_name
self.price = price
self.balance = 0
self.stock = 0
def add_funds(self, amount):
if self.stock == 0:
return f"Machine is out of stock. Here is your ${amount}."
self.balance += amount
return f"Current balance: ${self.balance}"
def restock(self, amount):
self.stock += amount
return f"Current {self.product_name} stock: {self.stock}"
def vend(self):
if self.stock == 0:
return "Machine is out of stock."
if self.balance < self.price:
return f"You must add ${self.price - self.balance} more funds."
change = self.balance - self.price
self.balance = 0
self.stock -= 1
if change == 0:
return f"Here is your {self.product_name}."
return f"Here is your {self.product_name} and ${change} change."
```
下面是针对输入输出的解释:
- `v = VendingMachine('candy', 10)`:创建一个售价为 $10 的糖果售货机。
- `v.vend()`:第一次购买,糖果售货机没有库存,返回 'Machine is out of stock.'。
- `v.add_funds(15)`:向糖果售货机添加 $15,但是糖果售货机没有库存,返回 'Machine is out of stock. Here is your $15.'。
- `v.restock(2)`:将糖果售货机的库存加 2,返回 'Current candy stock: 2'。
- `v.vend()`:第二次购买,糖果售货机的余额为 $0,但是商品的价格是 $10,返回 'You must add $10 more funds.'。
- `v.add_funds(7)`:向糖果售货机添加 $7,当前余额为 $7,返回 'Current balance: $7'。
- `v.vend()`:第三次购买,糖果售货机的余额为 $7,但是商品的价格是 $10,返回 'You must add $3 more funds.'。
- `v.add_funds(5)`:向糖果售货机添加 $5,当前余额为 $12,返回 'Current balance: $12'。
- `v.vend()`:第四次购买,糖果售货机的余额为 $12,商品的价格为 $10,返回 'Here is your candy and $2 change.'。
- `v.add_funds(10)`:第五次购买,糖果售货机的余额为 $0,但是没有库存,返回 'Machine is out of stock. Here is your $10.'。
- `w = VendingMachine('soda', 2)`:创建一个售价为 $2 的汽水售货机。
- `w.restock(3)`:将汽水售货机的库存加 3,返回 'Current soda stock: 3'。
- `w.restock(3)`:将汽水售货机的库存再次加 3,返回 'Current soda stock: 6'。
- `w.add_funds(2)`:向汽水售货机添加 $2,当前余额为 $2,返回 'Current balance: $2'。
- `w.vend()`:购买汽水,余额足够,返回 'Here is your soda.'。