python代码 将交通工具按图5-5所示进行分类,并按要求进行面向对象的编程。 vehicde(交通工具) 特性:能移动(m) train(火车) 特性:有轨道(t) automobile(汽车) 特性:有轮子(w) aircrali(飞机) 特性:有翅膀(f) car(小车) 特性:只载人(n) tnack(卡车) 特性:可以栽货物(g) (3)对car类增加颜色(color)属性,并参考5.1.2节对颜色(color)属性进行数据封装。 (4)采用多重继承的方式,在现有类的基础上定义一个能像飞机一样飞行的小汽车类(airraft-car).
时间: 2023-08-03 22:08:31 浏览: 72
以下是面向对象实现的 Python 代码:
```python
class Vehicle:
def __init__(self):
self.movable = True
class Train(Vehicle):
def __init__(self):
super().__init__()
self.has_track = True
class Automobile(Vehicle):
def __init__(self):
super().__init__()
self.has_wheel = True
class Aircraft(Vehicle):
def __init__(self):
super().__init__()
self.has_wing = True
class Car(Automobile):
def __init__(self):
super().__init__()
self.only_passenger = True
self.color = None
def set_color(self, color):
self.color = color
def get_color(self):
return self.color
class Truck(Automobile):
def __init__(self):
super().__init__()
self.can_carry_goods = True
class AircraftCar(Aircraft, Car):
def __init__(self):
super().__init__()
```
其中,`Vehicle` 是基类,包含了所有交通工具的共同特性,如能否移动。其他交通工具类都继承自 `Vehicle`,并增加了各自的特性。`Car` 类增加了一个 `color` 属性,并进行了数据封装。最后,`AircraftCar` 类继承自 `Aircraft` 和 `Car`,实现了能像飞机一样飞行的小汽车。