编写程序并测试,有一个汽车类Vehicle,类中的私有数据成员为车轮个数wheels和车重weight;小车类Car是汽车类vehicle派生类,其中包含载客人数passenger_load,默认4人;卡车类Truck是汽车类vehicle派生类,其中包含载客人数passenger_load和载重量payload。 提示:编写类时要使用get和set方法,Vehicle类定义display()显示车轮和重量,Car和Truck中要对display()进行同名覆盖。
时间: 2024-02-09 13:09:54 浏览: 69
浅析Ruby中的类对象的概念
以下是实现题目要求的代码:
```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("车轮个数:{},车重:{}吨".format(self.__wheels, self.__weight))
class Car(Vehicle):
def __init__(self, wheels, weight, passenger_load=4):
super().__init__(wheels, weight)
self.passenger_load = passenger_load
def display(self):
print("小车,车轮个数:{},车重:{}吨,载客人数:{}".format(self.get_wheels(), self.get_weight(), 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 display(self):
print("卡车,车轮个数:{},车重:{}吨,载客人数:{},载重量:{}吨".format(self.get_wheels(), self.get_weight(), self.passenger_load, self.payload))
```
我们可以进行下面的测试:
```python
car = Car(4, 0.5)
car.display()
truck = Truck(8, 5, 2, 10)
truck.display()
```
输出结果为:
```
小车,车轮个数:4,车重:0.5吨,载客人数:4
卡车,车轮个数:8,车重:5吨,载客人数:2,载重量:10吨
```
阅读全文