请用Python写一段智能停车场管理系统
时间: 2023-11-19 09:53:48 浏览: 52
好的,以下是一个简单的智能停车场管理系统的Python代码:
```python
class ParkingLot:
def __init__(self, capacity):
self.capacity = capacity
self.spaces = [False] * capacity
def park(self):
for i in range(self.capacity):
if not self.spaces[i]:
self.spaces[i] = True
return i
return -1
def leave(self, space):
if space >= 0 and space < self.capacity and self.spaces[space]:
self.spaces[space] = False
return True
return False
def available_spaces(self):
return self.capacity - sum(self.spaces)
def __str__(self):
return f"ParkingLot(capacity={self.capacity}, available_spaces={self.available_spaces()})"
if __name__ == "__main__":
parking_lot = ParkingLot(10)
print(parking_lot)
space = parking_lot.park()
if space >= 0:
print(f"Parked at space {space}")
else:
print("No available spaces")
print(parking_lot)
if parking_lot.leave(space):
print(f"Left space {space}")
else:
print(f"Failed to leave space {space}")
print(parking_lot)
```
这个系统使用一个类`ParkingLot`来表示停车场,其中`__init__`方法初始化停车场的容量和每个停车位的状态(是否被占用)。`park`方法用于停车,它会遍历所有停车位,找到第一个空位并将其占用,返回该停车位的编号。如果没有空位,则返回-1。`leave`方法用于离开停车场,它接受一个停车位的编号作为参数,如果该停车位被占用,则将其释放并返回True,否则返回False。`available_spaces`方法用于获取当前停车场的可用停车位数量。`__str__`方法用于将停车场对象转换为字符串,方便打印输出。
在主程序中,我们创建了一个容量为10的停车场对象,并进行了一次停车和离开的操作,最后打印出停车场的状态。