Fall 2020 Berkeley cs61a hw05答案
class VendingMachine :
"""A vending machine that vends some product for some price.
>>> v = VendingMachine('candy', 10)
>>> v.vend()
'Inventory empty. Restocking required.'
>>> v.add_funds(15)
'Inventory empty. Restocking required. 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)
'Inventory empty. Restocking required. 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.'
"""
"*** YOUR CODE HERE ***"
def __init__ ( self, product, price) :
self. funds = 0
self. price = price
self. inventory = 0
self. product = product
def add_funds ( self, added_money) :
self. funds = self. funds + added_money
if self. inventory == 0 :
self. refund = self. funds
self. funds = self. funds - added_money
return 'Inventory empty. Restocking required. Here is your ${0}.' . format ( self. refund)
return 'Current balance: ${0}' . format ( self. funds)
def restock ( self, restore_amount) :
self. inventory = self. inventory + restore_amount
return 'Current {0} stock: {1}' . format ( self. product, self. inventory)
def vend ( self) :
if self. inventory == 0 :
if self. funds == 0 :
return 'Inventory empty. Restocking required.'
else :
return 'Inventory empty. Restocking required. Here is your ${0}.' . format ( self. funds)
else :
if self.