2.编写程序并测试,有一个汽车类 Vehicle,类中的私有数据成员为车轮个数 wheels 和车重 weight;小车类 Car 是汽车类 vehicle 派生类,其中包含载客人数 passenger_load,默认 4 人;卡车类 Truck 是汽车类 vehicle 派生类,其中包含载 客人数 passenger_load 和载重量 payload。 提示:编写类时要使用 get 和 set 方法,Vehicle 类定义 display()显示车轮 和重量,Car 和 Truck 中要对 display()进行同名覆盖。
时间: 2024-02-13 14:06:52 浏览: 98
JAVA 课程实验设计
5星 · 资源好评率100%
好的,以下是符合您要求的 Python 代码:
```python
class Vehicle:
def __init__(self, wheels, weight):
self._wheels = wheels
self._weight = weight
def get_wheels(self):
return self._wheels
def set_wheels(self, wheels):
self._wheels = wheels
def get_weight(self):
return self._weight
def set_weight(self, weight):
self._weight = weight
def display(self):
print("Number of wheels:", self._wheels)
print("Weight:", self._weight, "kg")
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
def set_passenger_load(self, passenger_load):
self._passenger_load = passenger_load
def display(self):
super().display()
print("Passenger load:", 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 set_passenger_load(self, passenger_load):
self._passenger_load = passenger_load
def get_payload(self):
return self._payload
def set_payload(self, payload):
self._payload = payload
def display(self):
super().display()
print("Passenger load:", self._passenger_load)
print("Payload:", self._payload, "kg")
```
您可以使用以下代码进行测试:
```python
# test Vehicle class
vehicle = Vehicle(4, 1000)
vehicle.display()
# test Car class
car = Car(4, 800)
car.display()
car.set_passenger_load(5)
car.display()
# test Truck class
truck = Truck(6, 5000, 2, 10000)
truck.display()
truck.set_passenger_load(3)
truck.set_payload(8000)
truck.display()
```
输出如下:
```
Number of wheels: 4
Weight: 1000 kg
Number of wheels: 4
Weight: 800 kg
Passenger load: 4
Number of wheels: 4
Weight: 800 kg
Passenger load: 5
Number of wheels: 6
Weight: 5000 kg
Passenger load: 2
Payload: 10000 kg
Number of wheels: 6
Weight: 5000 kg
Passenger load: 3
Payload: 8000 kg
```
阅读全文