这一块内容对学习过面向对象思想的同学比较简单,废话不多说,直接来看案例。
封装
"""
使用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路公交车”,并打印(也包括属性和驾驶的方法)
"""
class bus(Origin.car):
def __init__(self, name, color, wheel_number, speed):
super().__init__(name, color, wheel_number, speed)
if __name__ == '__main__':
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路公交车的驾驶方法并打印
"""
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))
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))
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路公交车在开(用重写实现多态)
|