案例六:停车收费 使用面向对象编程模式,编写本案例中类的程序代码,完成测试主程序编程。 需求分析: 1.车辆的收费标准分为两类:注册车辆收取固定月租费(400元),临时车辆按时计费; 2.车辆出场时核查是否缴费,未缴费不得出场; 3.临时车辆的收费标准为:半小时内免费。超过半小时的,每小时8元,且不足一小时部 分也按一小时缴费,每日停车费100元封顶; 4.请开发针对两类车辆的计费程序。 5.本案例车辆类的类图如下: Vehicle plateNumber enrolled checkOut()
时间: 2024-02-06 15:10:06 浏览: 157
一个关于停车场的收费系统
以下是本案例中的类的程序代码,包括Vehicle类、RegisteredVehicle类和TemporaryVehicle类:
```python
class Vehicle:
def __init__(self, plateNumber):
self.plateNumber = plateNumber
self.enrolled = False
self.timeIn = None
self.timeOut = None
self.fee = 0
def checkOut(self):
if not self.enrolled:
return "Error: Vehicle has not been enrolled"
elif not self.timeOut:
return "Error: Vehicle has not checked out"
elif not self.fee:
return "Error: Vehicle has not paid"
duration = (self.timeOut - self.timeIn).total_seconds() / 3600
if duration <= 0.5:
self.fee = 0
elif duration > 0.5 and duration <= 1:
self.fee = 8
else:
self.fee = ((int(duration) - 1) * 8) + 8
if self.fee > 100:
self.fee = 100
return "Fee for {} is {} yuan".format(self.plateNumber, self.fee)
class RegisteredVehicle(Vehicle):
def __init__(self, plateNumber):
super().__init__(plateNumber)
self.enrolled = True
self.fee = 400
class TemporaryVehicle(Vehicle):
def __init__(self, plateNumber):
super().__init__(plateNumber)
def checkOut(self):
if not self.enrolled:
return "Error: Vehicle has not been enrolled"
elif not self.timeOut:
return "Error: Vehicle has not checked out"
elif not self.fee:
return "Error: Vehicle has not paid"
duration = (self.timeOut - self.timeIn).total_seconds() / 3600
if duration <= 0.5:
self.fee = 0
elif duration > 0.5 and duration <= 1:
self.fee = 8
else:
self.fee = ((int(duration) - 1) * 8) + 8
if self.fee > 100:
self.fee = 100
return "Fee for {} is {} yuan".format(self.plateNumber, self.fee)
```
以下是测试主程序的编程代码:
```python
import datetime
# create registered vehicle
vehicle1 = RegisteredVehicle("ABC123")
vehicle1.timeIn = datetime.datetime(2022, 1, 1, 12, 0)
vehicle1.timeOut = datetime.datetime(2022, 1, 1, 15, 0)
print(vehicle1.checkOut()) # expected output: Fee for ABC123 is 400 yuan
# create temporary vehicle
vehicle2 = TemporaryVehicle("XYZ789")
vehicle2.enrolled = True
vehicle2.timeIn = datetime.datetime(2022, 1, 1, 12, 0)
vehicle2.timeOut = datetime.datetime(2022, 1, 1, 13, 0)
print(vehicle2.checkOut()) # expected output: Fee for XYZ789 is 8 yuan
# create temporary vehicle with longer duration
vehicle3 = TemporaryVehicle("EFG456")
vehicle3.enrolled = True
vehicle3.timeIn = datetime.datetime(2022, 1, 1, 12, 0)
vehicle3.timeOut = datetime.datetime(2022, 1, 1, 17, 30)
print(vehicle3.checkOut()) # expected output: Fee for EFG456 is 100 yuan
```
阅读全文