将交通工具按图5-5所示进行分类,并按要求进行面向对象的编程。 vehicde(交通工具) 特性:能移动(m) train(火车) 特性:有轨道(t) automobile(汽车) 特性:有轮子(w) aircrali(飞机) 特性:有翅膀(f) car(小车) 特性:只载人(n) tnack(卡车) 特性:可以栽货物(g)
时间: 2023-07-30 12:09:04 浏览: 38
以下是面向对象编程的代码实现:
```python
class Vehicle:
def __init__(self, movable):
self.movable = movable
class Train(Vehicle):
def __init__(self):
super().__init__(True)
self.track = True
class Automobile(Vehicle):
def __init__(self):
super().__init__(True)
self.wheels = True
class Aircraft(Vehicle):
def __init__(self):
super().__init__(True)
self.wings = True
class Car(Automobile):
def __init__(self):
super().__init__()
self.passenger_only = True
class Truck(Automobile):
def __init__(self):
super().__init__()
self.cargo_loadable = True
```
其中,`Vehicle` 是所有交通工具的基类,包含一个 `movable` 属性,表示该交通工具是否可以移动。`Train`、`Automobile`、`Aircraft`、`Car` 和 `Truck` 都是 `Vehicle` 的子类,分别表示火车、汽车、飞机、小车和卡车。它们都继承了 `Vehicle` 的 `movable` 属性,并且添加了各自的特有属性。
例如,`Train` 添加了一个 `track` 属性,表示火车是有轨道的;`Automobile` 添加了一个 `wheels` 属性,表示汽车有轮子;`Aircraft` 添加了一个 `wings` 属性,表示飞机有翅膀;`Car` 添加了一个 `passenger_only` 属性,表示小车只能载人;`Truck` 添加了一个 `cargo_loadable` 属性,表示卡车可以载货物。