交通工具有多种多样,比如:汽车、火车、飞机等,一般的交通工具类的属性有:厂商,发动机型号,制作型号,时间;方法有:运行(输出速度),停止。 (1)请使用抽象方法实现交通工具类和方法:实现汽车、火车、飞机类,继承于交通工具类,实现他们不同的运行方法。 (2)Tom在出门去,不知道会乘坐什么交通工具,利用用户的输入值进行随机派遣(mod 3 ,根据余数随机决定交通工具),要求程序利用上转型对象完成编程。
时间: 2023-06-02 08:06:10 浏览: 78
(1)交通工具类和方法的抽象实现:
```python
from abc import ABC, abstractmethod
class Transportation(ABC):
@abstractmethod
def run(self):
pass
@abstractmethod
def stop(self):
pass
class Car(Transportation):
def __init__(self, brand, engine_model, production_model, year):
self.brand = brand
self.engine_model = engine_model
self.production_model = production_model
self.year = year
def run(self):
print("Car is running.")
def stop(self):
print("Car is stopped.")
class Train(Transportation):
def __init__(self, brand, engine_model, production_model, year):
self.brand = brand
self.engine_model = engine_model
self.production_model = production_model
self.year = year
def run(self):
print("Train is running.")
def stop(self):
print("Train is stopped.")
class Airplane(Transportation):
def __init__(self, brand, engine_model, production_model, year):
self.brand = brand
self.engine_model = engine_model
self.production_model = production_model
self.year = year
def run(self):
print("Airplane is flying.")
def stop(self):
print("Airplane is landed.")
```
(2)根据用户输入的随机值,随机派遣交通工具:
```python
import random
def dispatch_vehicle(num):
if num == 0:
return Car("Volvo", "XL-1000", "SUV-2", "2019")
elif num == 1:
return Train("CRH-500", "AC-1000", "Passenger-2", "2021")
elif num == 2:
return Airplane("Boeing", "PW-2000", "747-400", "2010")
else:
return None
# 随机生成模数
input_num = random.randint(1, 100)
vehicle = dispatch_vehicle(input_num % 3)
if vehicle is not None:
vehicle.run()
else:
print("No vehicle dispatched.")
```