编写程序并测试,有一个汽车类 Vehicle,类中的私有数据成员为车轮个数wheels 和车重 weight;小车类 Car 是汽车类 vehicle 派生类,其中包含载客人数passenger_load,默认 4 人;卡车类 Truck 是汽车类 vehicle 派生类,其中包含载客人数 passenger_load 和载重量 payload。
时间: 2024-02-15 19:02:26 浏览: 85
好的,这里是一个简单的实现,你可以参考一下:
```python
class Vehicle:
def __init__(self, wheels, weight):
self.__wheels = wheels
self.__weight = weight
def get_wheels(self):
return self.__wheels
def get_weight(self):
return self.__weight
class Car(Vehicle):
def __init__(self, wheels, weight, passenger_load=4):
super().__init__(wheels, weight)
self.__passenger_load = passenger_load
def get_passenger_load(self):
return self.__passenger_load
class Truck(Vehicle):
def __init__(self, wheels, weight, passenger_load, payload):
super().__init__(wheels, weight)
self.__passenger_load = passenger_load
self.__payload = payload
def get_passenger_load(self):
return self.__passenger_load
def get_payload(self):
return self.__payload
# 测试
car = Car(4, 1000) # 创建一辆小车,车轮数为4,车重为1000kg,默认载客人数为4人
print(f"小车的车轮个数为{car.get_wheels()},车重为{car.get_weight()}kg,载客人数为{car.get_passenger_load()}人")
truck = Truck(6, 5000, 2, 5000) # 创建一辆卡车,车轮数为6,车重为5000kg,载客人数为2人,载重量为5000kg
print(f"卡车的车轮个数为{truck.get_wheels()},车重为{truck.get_weight()}kg,载客人数为{truck.get_passenger_load()}人,载重量为{truck.get_payload()}kg")
```
输出结果如下:
```
小车的车轮个数为4,车重为1000kg,载客人数为4人
卡车的车轮个数为6,车重为5000kg,载客人数为2人,载重量为5000kg
```
阅读全文