写一个停车场收费系统的代码
时间: 2023-12-11 18:03:18 浏览: 204
一个关于停车场的收费系统
好的,以下是一个简单的停车场收费系统的代码示例:
```python
class ParkingLot:
def __init__(self, capacity):
self.capacity = capacity
self.spots = [None] * capacity
def park(self, vehicle):
if None not in self.spots:
return False
for i in range(self.capacity):
if self.spots[i] is None:
self.spots[i] = vehicle
return True
def unpark(self, spot):
if self.spots[spot] is None:
return False
self.spots[spot] = None
return True
class Vehicle:
def __init__(self, license):
self.license = license
class Car(Vehicle):
def __init__(self, license):
super().__init__(license)
self.fee = 5
class Truck(Vehicle):
def __init__(self, license):
super().__init__(license)
self.fee = 10
class Motorbike(Vehicle):
def __init__(self, license):
super().__init__(license)
self.fee = 3
class ParkingMeter:
def __init__(self, rate):
self.rate = rate
self.start_time = None
self.end_time = None
def start(self):
self.start_time = time.time()
def stop(self):
self.end_time = time.time()
def get_duration(self):
return self.end_time - self.start_time
def calculate_fee(self):
duration = self.get_duration()
return round(duration * self.rate, 2)
parking_lot = ParkingLot(50)
meter = ParkingMeter(0.1)
while True:
command = input("Enter command: park, unpark, or quit\n")
if command == "park":
license = input("Enter license plate number:\n")
vehicle_type = input("Enter vehicle type (car, truck, or motorbike):\n")
if vehicle_type == "car":
vehicle = Car(license)
elif vehicle_type == "truck":
vehicle = Truck(license)
elif vehicle_type == "motorbike":
vehicle = Motorbike(license)
else:
print("Invalid vehicle type")
continue
if parking_lot.park(vehicle):
print("Vehicle parked")
meter.start()
else:
print("Parking lot full")
elif command == "unpark":
spot = input("Enter spot number:\n")
if parking_lot.unpark(int(spot)):
meter.stop()
fee = meter.calculate_fee()
print("Vehicle unparked. Fee: $", fee)
else:
print("Invalid spot number")
elif command == "quit":
break
else:
print("Invalid command")
```
这个代码示例包括了停车场类、车辆类、计费器类和一个简单的用户界面,可以让用户通过命令行输入来模拟停车和取车的过程。其中,计费器类使用了 Python 内置的 time 模块来计算停车时间,并根据每分钟的收费率计算出停车费用。如果需要更复杂的功能,可以根据实际需求进行修改和扩展。
阅读全文