python学习之【继承、封装、多态】
# 定义一个基类Vehicle
class Vehicle:
def __init__(self, power):
self.power = power
self.speed = 0
def start(self):
print("Vehicle starting...")
def stop(self):
self.speed = 0
print("Vehicle stopping...")
# 定义一个派生类Car,继承自Vehicle
class Car(Vehicle):
def __init__(self, power, color):
# 使用super()函数调用基类的__init__方法
super().__init__(power)
self.color = color
def wash(self):
print("Washing a " + self.color + " car.")
# 定义一个派生类Motorcycle,继承自Vehicle
class Motorcycle(Vehicle):
def __init__(self, power):
super().__init__(power)
self.speed_range = (0, 15)
def speed_up(self):
if self.speed < self.speed_range[1]:
self.speed += 1
print("Speed up to", self.speed)
else:
print("Speed cannot exceed", self.speed_range[1])
# 实例化对象
my_car = Car('Electric', 'Silver')
my_motorcycle = Motorcycle('Electric')
# 使用对象的方法
my_car.wash()
my_motorcycle.speed_up()
这个代码示例展示了如何在Python中使用类继承和初始化,以及如何重用基类的方法。Car
类继承自Vehicle
类,并添加了wash
方法。Motorcycle
类也继承自Vehicle
类,并添加了speed_up
方法来控制速度。代码简洁,易于理解,适合学习继承的初步。
评论已关闭