设计以下类 .飞机 发动机 .鸟 翅膀 .火箭 空气动力 .热气球 氢气 通过多态,演示各种飞行行为
时间: 2024-04-10 18:27:42 浏览: 19
以下是对应的类设计:
```python
class Vehicle:
def fly(self):
pass
class Airplane(Vehicle):
def __init__(self, engine):
self.engine = engine
def fly(self):
print("Airplane is flying with the engine.")
class Bird(Vehicle):
def __init__(self, wings):
self.wings = wings
def fly(self):
print("Bird is flying with its wings.")
class Rocket(Vehicle):
def __init__(self, air_thrust):
self.air_thrust = air_thrust
def fly(self):
print("Rocket is flying with the air propulsion.")
class HotAirBalloon(Vehicle):
def __init__(self, gas):
self.gas = gas
def fly(self):
print("Hot air balloon is flying using hydrogen gas.")
# 示例使用
engine = "Jet Engine"
airplane = Airplane(engine)
airplane.fly()
wings = "Feathers"
bird = Bird(wings)
bird.fly()
air_thrust = "Rocket Engine"
rocket = Rocket(air_thrust)
rocket.fly()
gas = "Hydrogen"
hot_air_balloon = HotAirBalloon(gas)
hot_air_balloon.fly()
```
在上面的示例代码中,定义了一个基类 `Vehicle`,它有一个 `fly` 方法。然后分别定义了 `Airplane`、`Bird`、`Rocket` 和 `HotAirBalloon` 这四个类,它们都继承自 `Vehicle`。每个子类都实现了 `fly` 方法,分别展示了不同的飞行行为。通过多态,我们可以调用相同的方法名 `fly`,但根据对象的不同,会执行对应类中的方法。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)