3)某商店经销一种货物,货物成箱购进,成箱卖出,购进和卖出时以重最为单位,各箱的 重量可能不一样,商店需要记录目前库存的总重量。编写程序,通过定义类Cargo模拟商 店货物购进和卖出的情况。
时间: 2024-10-25 09:16:41 浏览: 46
在这个模拟中,我们可以创建一个名为`Cargo`的类,它将包含以下属性和方法:
1. 属性:
- `weight`:表示每箱货物的重量,以公斤为单位,作为一个实例变量存储。
- `stock`:列表或集合,用于存储所有已购进的货物箱子及其重量。
2. 方法:
- `purchase(weight)`:进货方法,接收新的货物重量,将其添加到库存中。
- `sell(weight)`:销售方法,接受客户购买的货物重量,从库存中减去相应的重量并返回实际售出的数量。
- `get_total_weight()`:获取当前库存的总重量。
下面是简单的Python代码实现:
```python
class Cargo:
def __init__(self):
self.stock = []
def purchase(self, weight):
self.stock.append(weight)
def sell(self, requested_weight):
if requested_weight > 0 and requested_weight <= sum(self.stock): # 确保有足够的库存
for i in range(len(self.stock)):
if self.stock[i] >= requested_weight:
self.stock[i] -= requested_weight
return requested_weight
else:
print("请求的重量大于剩余库存")
return 0
else:
print("无效的请求,无法出售")
return 0
def get_total_weight(self):
return sum(self.stock)
```
使用这个`Cargo`类,商店就可以有效地管理他们的货物库存了。例如:
```python
store = Cargo()
store.purchase(50) # 购进50公斤货物
print(store.get_total_weight()) # 输出50
store.sell(20) # 销售20公斤
print(store.get_total_weight())
阅读全文
相关推荐














