输出客车的基本信息(品牌、颜色、座位数)、货车的基本信息(品牌、颜色、载重量); 要求程序可执行,体现封装性、继承性和多态性
时间: 2023-09-17 10:13:48 浏览: 69
好的,我可以为您编写一个简单的程序来实现这个要求。
```python
class Vehicle:
def __init__(self, brand, color):
self.brand = brand
self.color = color
class Bus(Vehicle):
def __init__(self, brand, color, seats):
super().__init__(brand, color)
self.seats = seats
def display_info(self):
print(f"Bus - Brand: {self.brand}, Color: {self.color}, Seats: {self.seats}")
class Truck(Vehicle):
def __init__(self, brand, color, load_capacity):
super().__init__(brand, color)
self.load_capacity = load_capacity
def display_info(self):
print(f"Truck - Brand: {self.brand}, Color: {self.color}, Load Capacity: {self.load_capacity} tons")
# 测试
bus = Bus("Toyota", "Blue", 45)
bus.display_info()
truck = Truck("Volvo", "Red", 10)
truck.display_info()
```
上面的代码中,我们定义了一个基类 `Vehicle`,它有两个属性 `brand` 和 `color`。然后我们定义了两个子类 `Bus` 和 `Truck`,它们都继承了 `Vehicle` 类。
`Bus` 类有一个额外的属性 `seats`,表示座位数。它还有一个 `display_info` 方法,用于显示客车的基本信息。
`Truck` 类有一个额外的属性 `load_capacity`,表示载重量(单位:吨)。它也有一个 `display_info` 方法,用于显示货车的基本信息。
在测试部分,我们创建了一个客车对象和一个货车对象,并分别调用它们的 `display_info` 方法来显示它们的基本信息。这样,我们就实现了封装性、继承性和多态性。
阅读全文
相关推荐
















