设计一个名为Vehicle的抽象基类,这个基类包含:名称、颜色、门的数量、气缸数量、变速箱类型和油位表示。在添加一个名为horn的函数用来显示Vehicle喇叭发出的声音。print函数用来显示信息。horn函数和print函数都应该是虚函数。horn是个纯虚函数。类Taxi和Truck是派生类。 编写一个类的测试结构要求:将一个Taxi类型的对象和一个Truck类型的对象实例化,并创建一个基类指针数组分别指向这两个对象。 程序输出如下: Taxi: Number of doors:4 Number of cylinders:6 Transmission type:5 Color :yellow Fuel level:3.3 Truck: Number of doors:2 Number of cylinders:16 Transmission type:8 Color :black Fuel level:7.54 Taxi:beep beep! Truck:HOOOONK!
时间: 2024-03-23 11:40:44 浏览: 109
实现了一个PHP5的getter/setter基类的代码
好的,下面是代码实现:
```python
from abc import ABC, abstractmethod
class Vehicle(ABC):
def __init__(self, name, color, num_doors, num_cylinders, transmission_type, fuel_level):
self.name = name
self.color = color
self.num_doors = num_doors
self.num_cylinders = num_cylinders
self.transmission_type = transmission_type
self.fuel_level = fuel_level
@abstractmethod
def horn(self):
pass
@abstractmethod
def print_info(self):
pass
class Taxi(Vehicle):
def __init__(self, name, color, num_doors, num_cylinders, transmission_type, fuel_level):
super().__init__(name, color, num_doors, num_cylinders, transmission_type, fuel_level)
def horn(self):
print("beep beep!")
def print_info(self):
print(f"{self.name}: Number of doors:{self.num_doors} Number of cylinders:{self.num_cylinders} Transmission type:{self.transmission_type} Color :{self.color} Fuel level:{self.fuel_level}")
class Truck(Vehicle):
def __init__(self, name, color, num_doors, num_cylinders, transmission_type, fuel_level):
super().__init__(name, color, num_doors, num_cylinders, transmission_type, fuel_level)
def horn(self):
print("HOOOONK!")
def print_info(self):
print(f"{self.name}: Number of doors:{self.num_doors} Number of cylinders:{self.num_cylinders} Transmission type:{self.transmission_type} Color :{self.color} Fuel level:{self.fuel_level}")
if __name__ == '__main__':
taxi = Taxi("Taxi", "yellow", 4, 6, 5, 3.3)
truck = Truck("Truck", "black", 2, 16, 8, 7.54)
vehicles = [taxi, truck]
for vehicle in vehicles:
vehicle.print_info()
vehicle.horn()
```
程序输出如下:
```
Taxi: Number of doors:4 Number of cylinders:6 Transmission type:5 Color :yellow Fuel level:3.3
beep beep!
Truck: Number of doors:2 Number of cylinders:16 Transmission type:8 Color :black Fuel level:7.54
HOOOONK!
```
阅读全文