生活随笔
收集整理的这篇文章主要介绍了
Python类的多态
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
多态:不同的子类对象调用相同的方法,产生不同的执行结果
我还是通过对火车站信息查询的代码理解多态,代码如下:
#类的多态 作者:肖俊怡
from prettytable import PrettyTableclass Ticket():def __init__(self,cf_station,dd_station,cf_time,dd_time,checi,none_set):self.cf_station = cf_stationself.dd_station = dd_stationself.cf_time = cf_timeself.dd_time = dd_timeself.checi = checiself.none_set = none_setclass Gd(Ticket):def __init__(self,cf_station,dd_station,cf_time,dd_time,checi,yideng,erdeng,none_set):Ticket.__init__(self,cf_station,dd_station,cf_time,dd_time,checi,none_set)self.yideng = yidengself.erdeng = erdengdef insert(self,pt):pt.add_row([self.cf_station,self.dd_station,self.cf_time,self.dd_time,self.checi,self.yideng,self.erdeng,self.none_set])class TKz(Ticket):def __init__(self,cf_station,dd_station,cf_time,dd_time,checi,ruanwo,yingwo,yingzuo,none_set):Ticket.__init__(self,cf_station,dd_station,cf_time,dd_time,checi,none_set)self.ruanwo = ruanwoself.yingwo = yingwoself.yingzuo = yingzuo def insert(self,pt):pt.add_row([self.cf_station,self.dd_station,self.cf_time,self.dd_time,self.checi,self.ruanwo,self.yingwo,self.yingzuo,self.none_set])#创建类的实例
g1 = Gd("西安", "北京", "10:00", "15:00", "G33", 1, 2, 3 )
g2 = Gd("西安", "沈阳", "17:00", "23:59", "G1", 0, 9, 1)
T1 = TKz("北京","上海"," 2:00"," 4:00"," T11", 1, 2, 4, 10)
T2 = TKz("北京","长春"," 12:00"," 14:00"," T22", 11, 12, 14, 10)ptable = PrettyTable("出发站 到达站 出发时间 到达时间 车次 一等座 二等座 无座".split())
for i in [g1,g2]:i.insert(ptable)
print(ptable)ptable = PrettyTable("出发站 到达站 出发时间 到达时间 车次 软卧 硬卧 硬座 无座".split())
for i in [T1,T2]:i.insert(ptable)
print(ptable)
有上述代码可以见得:
不同子类中均定义了insert()方法,但是输出的结果并不一样,如下图
同时,还可以发现若子类无该方法,变查找其父类是否存在该方法并调用;
嗯嗯~~就这样!!
总结
以上是生活随笔为你收集整理的Python类的多态的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。