编写程序并测试,有一个汽车类 Vehicle ,类中的私有数据成员为车轮个数 wheels 和车重 weight :小车类 Car 是汽车类 vehicle 派生类 其中包含载客人数 passenger _ load ,默认4人;卡车类 Truck 是汽车类 vehicle 派生类,其中包含载客人数 passenger _ load 和载重量 payload 。 提示:编写类时要使用 get 和 set 方法, Vehicle 类定义 display ()显示车轮和重量, Car 和 Truck 中要对 display ()进行同名覆盖。
时间: 2024-01-22 09:18:23 浏览: 70
设计一个Car类
以下是Python代码实现:
```python
class Vehicle:
def __init__(self, wheels=4, weight=1000):
self.__wheels = wheels
self.__weight = weight
def set_wheels(self, wheels):
self.__wheels = wheels
def set_weight(self, weight):
self.__weight = weight
def get_wheels(self):
return self.__wheels
def get_weight(self):
return self.__weight
def display(self):
print("Wheels:", self.__wheels)
print("Weight:", self.__weight)
class Car(Vehicle):
def __init__(self, passenger_load=4):
super().__init__()
self.__passenger_load = passenger_load
def set_passenger_load(self, passenger_load):
self.__passenger_load = passenger_load
def get_passenger_load(self):
return self.__passenger_load
def display(self):
super().display()
print("Passenger load:", self.__passenger_load)
class Truck(Vehicle):
def __init__(self, passenger_load=2, payload=5000):
super().__init__()
self.__passenger_load = passenger_load
self.__payload = payload
def set_passenger_load(self, passenger_load):
self.__passenger_load = passenger_load
def set_payload(self, payload):
self.__payload = payload
def get_passenger_load(self):
return self.__passenger_load
def get_payload(self):
return self.__payload
def display(self):
super().display()
print("Passenger load:", self.__passenger_load)
print("Payload:", self.__payload)
# 测试代码
car1 = Car()
car1.display()
car1.set_wheels(6)
car1.set_weight(1200)
car1.set_passenger_load(5)
car1.display()
truck1 = Truck()
truck1.display()
truck1.set_wheels(8)
truck1.set_weight(10000)
truck1.set_passenger_load(3)
truck1.set_payload(10000)
truck1.display()
```
输出结果如下:
```
Wheels: 4
Weight: 1000
Passenger load: 4
Wheels: 6
Weight: 1200
Passenger load: 5
Wheels: 4
Weight: 1000
Passenger load: 2
Payload: 5000
Wheels: 8
Weight: 10000
Passenger load: 3
Payload: 10000
```
阅读全文