python 第3关:交通工具类的继承和多态
时间: 2024-04-18 22:19:40 浏览: 164
Python3.5面向对象程序设计之类的继承和多态详解
交通工具类可以作为一个父类,派生出汽车类、自行车类等子类。这些子类可以继承交通工具类的属性和方法,并且可以根据自身特点进行重写或者扩展。这就是面向对象编程中的继承和多态。
下面是一个简单的示例代码:
```python
class Vehicle:
def __init__(self, name, speed):
self.name = name
self.speed = speed
def run(self):
print(f"{self.name} is running at a speed of {self.speed} km/h.")
class Car(Vehicle):
def __init__(self, name, speed, brand):
super().__init__(name, speed)
self.brand = brand
def run(self):
print(f"{self.brand} {self.name} is running at a speed of {self.speed} km/h.")
class Bicycle(Vehicle):
def __init__(self, name, speed, type):
super().__init__(name, speed)
self.type = type
def run(self):
print(f"{self.type} {self.name} is running at a speed of {self.speed} km/h.")
car = Car("SUV", 120, "BMW")
car.run() # 输出:BMW SUV is running at a speed of 120 km/h.
bicycle = Bicycle("Mountain Bike", 30, "Off-road")
bicycle.run() # 输出:Off-road Mountain Bike is running at a speed of 30 km/h.
```
在上面的代码中,我们定义了一个交通工具类`Vehicle`,并且派生出了汽车类`Car`和自行车类`Bicycle`。这两个子类都继承了父类`Vehicle`的属性和方法,并且根据自身特点进行了重写或者扩展。在实例化子类对象后,我们可以调用它们的`run()`方法,这里展示了多态的特性,即不同的子类对象调用同一个方法,会有不同的输出结果。
阅读全文