Create a class called VendingMachine that represents a vending machine for some product. A VendingMachine object returns strings describing its interactions. Fill in the VendingMachine class, adding attributes and methods as appropriate, such that its behavior matches the following doctests:
时间: 2024-03-03 22:50:57 浏览: 62
CS31_Practice_Final.pdf
Sure, here's an implementation of the `VendingMachine` class that satisfies the given requirements:
```python
class VendingMachine:
def __init__(self, product_name, price):
self.product_name = product_name
self.price = price
self.balance = 0
self.stock = 0
def restock(self, amount):
self.stock += amount
return f"Current {self.product_name} stock: {self.stock}"
def deposit(self, amount):
if self.stock == 0:
return f"Machine is out of stock. Here is your ${amount} back."
self.balance += amount
return f"Current balance: ${self.balance}"
def vend(self):
if self.stock == 0:
return "Machine is out of stock."
if self.balance < self.price:
return f"You must deposit ${self.price - self.balance} more."
self.stock -= 1
self.balance -= self.price
if self.balance == 0:
return f"Here is your {self.product_name}."
return f"Here is your {self.product_name} and ${self.balance} change."
```
Here are the doctests to verify the behavior:
```python
# Create a vending machine that sells chips for $1.50
>>> machine = VendingMachine('chips', 1.50)
# Restock the machine with 10 chips
>>> machine.restock(10)
'Current chips stock: 10'
# Deposit $1.00 into the machine
>>> machine.deposit(1.00)
'Current balance: $1.00'
# Vend a chip with only $1.00 deposited
>>> machine.vend()
'You must deposit $0.50 more.'
# Deposit $1.50 into the machine
>>> machine.deposit(1.50)
'Current balance: $2.50'
# Vend a chip with $2.50 deposited
>>> machine.vend()
'Here is your chips and $1.00 change.'
# Vend a chip when the machine is out of stock
>>> machine.vend()
'Machine is out of stock.'
# Deposit $1.00 into an empty machine
>>> machine.deposit(1.00)
'Machine is out of stock. Here is your $1.00 back.'
```
阅读全文