简单的面向对象之衣柜管理系统代码
时间: 2023-08-06 13:22:14 浏览: 42
好的,以下是一个简单的面向对象的衣柜管理系统的代码:
```python
class Closet:
def __init__(self, capacity):
self.capacity = capacity
self.items = []
def add_item(self, item):
if len(self.items) < self.capacity:
self.items.append(item)
print(f"Item {item} added to the closet.")
else:
print(f"Closet is full.")
def remove_item(self, item):
if item in self.items:
self.items.remove(item)
print(f"Item {item} removed from the closet.")
else:
print(f"Item {item} not found in the closet.")
def list_items(self):
if len(self.items) > 0:
print("Items in the closet:")
for item in self.items:
print(item)
else:
print("Closet is empty.")
class Item:
def __init__(self, name, color, material):
self.name = name
self.color = color
self.material = material
def __str__(self):
return f"{self.color} {self.material} {self.name}"
closet = Closet(10)
while True:
print("1. Add item")
print("2. Remove item")
print("3. List items")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == "1":
name = input("Enter item name: ")
color = input("Enter item color: ")
material = input("Enter item material: ")
item = Item(name, color, material)
closet.add_item(item)
elif choice == "2":
name = input("Enter item name: ")
color = input("Enter item color: ")
material = input("Enter item material: ")
item = Item(name, color, material)
closet.remove_item(item)
elif choice == "3":
closet.list_items()
elif choice == "4":
break
else:
print("Invalid choice. Please try again.")
```
这个系统包括两个类,`Closet` 和 `Item`,以及一个主函数。`Closet` 类表示衣柜,有一个容量属性和一个物品列表。它有三个方法:`add_item()`,`remove_item()` 和 `list_items()`,分别用于添加物品、移除物品和列出衣柜中的物品。`Item` 类表示衣柜中的物品,有一个名称、颜色和材料属性。在主函数中,使用一个循环来不断接收用户的输入,并根据输入的选项来调用 `Closet` 对象的不同方法。