编写程序并测试,有一个汽车类 Vehicle,类中的私有数据成员为车轮个数 wheels 和车重 weight;小车类 Car 是汽车类 vehicle 派生类,其中包含载客人数 passenger_load,默认 4 人;卡车类 Truck 是汽车类 vehicle 派生类,其中包含载 客人数 passenger_load 和载重量 payload。 提示:编写类时要使用 get 和 set 方法,Vehicle 类定义 display()显示车轮 和重量,Car 和 Truck 中要对 display()进行同名覆盖。
时间: 2024-01-22 22:18:42 浏览: 109
以下是具体的程序实现:
```python
class Vehicle:
def __init__(self, wheels=0, weight=0):
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("车轮个数:{},车重:{}吨".format(self._wheels, self._weight))
class Car(Vehicle):
def __init__(self, passenger_load=4, wheels=4, weight=1.5):
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):
print("小车,车轮个数:{},车重:{}吨,载客人数:{}人".format(self._wheels, self._weight, self._passenger_load))
class Truck(Vehicle):
def __init__(self, passenger_load=2, payload=5, wheels=6, weight=10):
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):
print("卡车,车轮个数:{},车重:{}吨,载客人数:{}人,载重量:{}吨".format(
self._wheels, self._weight, self._passenger_load, self._payload))
```
我们可以进行一些简单的测试:
```python
car = Car()
car.display() # 小车,车轮个数:4,车重:1.5吨,载客人数:4人
car.set_passenger_load(5)
car.display() # 小车,车轮个数:4,车重:1.5吨,载客人数:5人
truck = Truck()
truck.display() # 卡车,车轮个数:6,车重:10吨,载客人数:2人,载重量:5吨
truck.set_payload(8)
truck.display() # 卡车,车轮个数:6,车重:10吨,载客人数:2人,载重量:8吨
```
阅读全文