马士兵Python学习笔记_P165_164.实操案例十三
一、实操案例十三
![在这里插入图片描述](https://img-blog.csdnimg.cn/d29fba77b73f467ab59a0ea93d5d97a5.png)
二、代码示例-编写程序实现乐手弹奏乐器
class Instrument():
def make_sound(self):
pass
class Erhu(Instrument):
def make_sound(self):
print("二胡在演奏")
class Piano(Instrument):
def make_sound(self):
print("钢琴在演奏")
class Violin(Instrument):
def make_sound(self):
print("小提琴在演奏")
def play(instrument):
instrument.make_sound()
class Bird():
def make_sound(self):
print("小鸟在唱歌")
if __name__ == '__main__':
play(Erhu())
play(Piano())
play(Violin())
play(Bird())
运行结果
D:\Environment\Python\Python311\python.exe D:\Environment\PythonWorks\learnPython\马士兵Python\第17章_实操案例\P165_164.实操案例十三_1编写程序实现乐手弹奏乐器.py
二胡在演奏
钢琴在演奏
小提琴在演奏
小鸟在唱歌
Process finished with exit code 0
三、代码示例-自定义类描述出租车和家用轿车信息
class Car(object):
def __init__(self, type, no):
self.type = type
self.no = no
def start(self):
pass
def stop(self):
pass
class Taxi(Car):
def __init__(self, type, no, company):
super().__init__(type, no)
self.company = company
def start(self):
print("乘客您好!")
print(f"我是{self.company}出租车公司的,我的车牌是:{self.no},您要去哪里?")
def stop(self):
print("目的地到了,请您付费下车,欢迎再次乘坐")
class PrivateCar(Car):
def __init__(self, type, no, name):
super().__init__(type, no)
self.name = name
def start(self):
print(f"我是{self.name},我的汽车我做主")
def stop(self):
print("目的地到了,我们去玩吧")
if __name__ == '__main__':
taxi = Taxi("宝马", "京A88888", "长城")
taxi.start()
taxi.stop()
print("-"*30)
private_car = PrivateCar("上海大众", "京A88899", "武大郎")
private_car.start()
private_car.stop()
运行结果
D:\Environment\Python\Python311\python.exe D:\Environment\PythonWorks\learnPython\马士兵Python\第17章_实操案例\P165_164.实操案例十三_2自定义类描述出租车和家用轿车信息.py
乘客您好!
我是长城出租车公司的,我的车牌是:京A88888,您要去哪里?
目的地到了,请您付费下车,欢迎再次乘坐
------------------------------
我是武大郎,我的汽车我做主
目的地到了,我们去玩吧
Process finished with exit code 0
B站视频链接:https://www.bilibili.com/video/BV1wD4y1o7AS?p=165