本文實(shí)例分析了python中類的一些方法,分享給大家供大家參考。具體分析如下:
先來(lái)看看下面這段代碼:
?12345678910 class Super: def delegate(self): self.action() class Provider(Super): def action(self): print 'in Provider.action' x = Provider() x.delegate()
本文實(shí)例運(yùn)行環(huán)境為Python2.7.6
運(yùn)行結(jié)果如下:
in Provider.action
在Super類中定義delegate()方法,delegate中調(diào)用self.action,在Provider子類中實(shí)現(xiàn)action方法。子類調(diào)用父類的delegate方法時(shí),實(shí)際是調(diào)用自己的action方法。。
總之一句話:
這里子類實(shí)現(xiàn)了父類delegate中所期望的action方法
再來(lái)看看下面這段代碼:
?12345678910111213141516171819202122232425262728293031323334353637 class Super: def delegate(self): self.action() def method(self): print 'super method' class Inherit(Super): pass class Replace(Super): def method(self): print "replace method" class Extended(Super): def method(self): print 'in extended class' Super.method(self) print 'out extended class' class Provider(Super): def action(self): print 'in Provider.action' x = Inherit() x.method() print '*'*50 y = Replace() y.method() print '*'*50 z = Extended() z.method() print '*'*50 x = Provider() x.delegate()
運(yùn)行結(jié)果如下:
?123456789 super method ************************************************** replace method ************************************************** in extended class super method out extended class ************************************************** in Provider.action
分別繼承父類的方法,替換父類的方法,擴(kuò)展了父類的方法
Super類定義了delegate方法并期待子類實(shí)現(xiàn)action函數(shù),Provider子類實(shí)現(xiàn)了action方法.
相信本文所述對(duì)大家Python程序設(shè)計(jì)的學(xué)習(xí)有一定的借鑒價(jià)值。
更多信息請(qǐng)查看IT技術(shù)專欄