生活随笔
收集整理的這篇文章主要介紹了
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类的多态的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。