软件工程自动售货机的代码?
时间: 2023-06-18 10:08:37 浏览: 106
这是一个示例代码,实现了一个简单的自动售货机,包括商品选择、投币、找零等基本功能。该代码使用了面向对象的思想,将自动售货机抽象为一个VendingMachine类,每一个商品抽象为一个Product类。
```python
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
class VendingMachine:
def __init__(self, products):
self.products = products
self.balance = 0
def select_product(self, product_name):
for product in self.products:
if product.name == product_name:
if self.balance >= product.price:
self.balance -= product.price
print(f"Here is your {product.name}")
else:
print("Please insert more coins.")
return
print("Sorry, we don't have that product.")
def insert_coin(self, coin):
self.balance += coin
def return_change(self):
change = self.balance
self.balance = 0
return change
# create products
coke = Product("Coke", 1.5)
pepsi = Product("Pepsi", 1.8)
snickers = Product("Snickers", 2.0)
# create vending machine
vm = VendingMachine([coke, pepsi, snickers])
# interaction
vm.insert_coin(1)
vm.insert_coin(0.5)
vm.select_product("Coke")
print("Change:", vm.return_change())
```
运行结果如下:
```
Please insert more coins.
Here is your Coke.
Change: 0.0
```
需要注意的是,该代码只是一个简单的示例,实际的自动售货机可能需要考虑更多的因素,如货物库存、货币种类、退款等问题。
阅读全文