这一块内容对学习过面向对象思想的同学比较简单,废话不多说,直接来看案例。
""" 使用python,选择小汽车和客车为对象,使用类实现它们的属性和方 法(汽车的重量属性,驾驶的方法),并打印属性 """ class car: # 构造方法,对属性进行初始化 def __init__(self, name, color, wheel_number, speed): self.color = color self.name = name self.wheel_number = wheel_number self.speed = speed # 打印属性信息 def print_car_info(self): print("{}有{}个轮子,颜色是{},速度是{}km/h".format(self.name, self.wheel_number, self.color, self.speed)) # 公用方法 def drive_car(self): print("车子在开") if __name__ == '__main__': # 实例化小汽车对象 sedan = car("小汽车", "红色", 4, 100) sedan.print_car_info() sedan.drive_car() # 实例化卡车对象 truck = car("大卡车", "蓝色", 6, 120) truck.print_car_info() truck.drive_car()
打印结果:
小汽车有4个轮子,颜色是红色,速度是100km/h 车子在开 大卡车有6个轮子,颜色是蓝色,速度是120km/h 车子在开
import Origin """ 对第一个问题改写:继承客车的属性和方法,改造为公交车,输入的 名字为:“东风路28路公交车”,并打印(也包括属性和驾驶的方法) """ # bus子类,继承car类 class bus(Origin.car): def __init__(self, name, color, wheel_number, speed): super().__init__(name, color, wheel_number, speed) if __name__ == '__main__': # 实例化bus对象 a_bus = bus("东风路28路公交车", "绿色", 6, 120) # 调用父类的方法 a_bus.print_car_info() # 调用父类的方法 a_bus.drive_car()
打印结果:
东风路28路公交车有6个轮子,颜色是绿色,速度是120km/h 车子在开
from Origin import car """ 使用多态实现28路、906路、B32路公交车的驾驶方法并打印 """ # 28路公交车继承自car类,对drive_car方法重写实现多态 class Twenty_Eight_bus(car): def __init__(self, name, color, wheel_number, speed): super().__init__(name, color, wheel_number, speed) def drive_car(self): print("{}在开(用重写实现多态)".format(self.name)) # 906路公交车继承自car类,对drive_car方法重写实现多态 class Nine_Zero_Six_bus(car): def __init__(self, name, color, wheel_number, speed): super().__init__(name, color, wheel_number, speed) def drive_car(self): print("{}在开(用重写实现多态)".format(self.name)) # B32路公交车继承自car类,对drive_car方法重写实现多态 class B_Three_Two_bus(car): def __init__(self, name, color, wheel_number, speed): super().__init__(name, color, wheel_number, speed) def drive_car(self): print("{}在开(用重写实现多态)".format(self.name)) if __name__ == '__main__': Twenty_Eight_bus = Twenty_Eight_bus("东风路28路公交车", "绿色", 6, 120) # 打印方法 Twenty_Eight_bus.drive_car() Nine_Zero_Six_bus = Nine_Zero_Six_bus("906路公交车", "黄色", 6, 120) # 打印方法 Nine_Zero_Six_bus.drive_car() B_Three_Two_bus = B_Three_Two_bus("B32路公交车", "红色", 6, 120) # 打印方法 B_Three_Two_bus.drive_car()
打印结果:
东风路28路公交车在开(用重写实现多态) 906路公交车在开(用重写实现多态) B32路公交车在开(用重写实现多态)