构建类MySedan继承上面的类MyCar, 要求在MySedan类中定义属性 n_wheel, n_doors,并定义自己的run方法(其中内容可自行设计);生成MySedan类的实例化对象bmw,打印出bmw所能调用的所有属性值,并采用bmw调用run方法。
时间: 2024-03-10 16:47:30 浏览: 52
好的,这是一个关于Python面向对象编程的问题,下面是代码实现:
class MyCar:
def __init__(self, brand, color):
self.brand = brand
self.color = color
def start(self):
print(f"{self.color} {self.brand} is starting.")
def stop(self):
print(f"{self.color} {self.brand} is stopping.")
class MySedan(MyCar):
def __init__(self, brand, color, n_wheels, n_doors):
super().__init__(brand, color)
self.n_wheels = n_wheels
self.n_doors = n_doors
def run(self):
print(f"{self.color} {self.brand} is running on {self.n_wheels} wheels.")
bmw = MySedan("BMW", "black", 4, 4)
print(f"Brand: {bmw.brand}")
print(f"Color: {bmw.color}")
print(f"Number of wheels: {bmw.n_wheels}")
print(f"Number of doors: {bmw.n_doors}")
bmw.run()
代码的解释:
- 首先定义了一个MyCar类,包含两个属性brand和color,以及start和stop方法;
- 然后定义一个MySedan类,继承自MyCar类,并增加了两个属性n_wheels和n_doors,以及自己的run方法;
- 最后创建了一个MySedan类的实例化对象bmw,并打印出了它的所有属性值,最后调用了bmw的run方法。
输出结果如下:
Brand: BMW
Color: black
Number of wheels: 4
Number of doors: 4
black BMW is running on 4 wheels.
希望这个代码能够解决你的问题。
相关推荐

















