本文實(shí)例分析了python中類(lèi)的一些方法,分享給大家供大家參考。具體分析如下:
先來(lái)看看下面這段代碼:
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類(lèi)中定義delegate()方法,delegate中調(diào)用self.action,在Provider子類(lèi)中實(shí)現(xiàn)action方法。子類(lèi)調(diào)用父類(lèi)的delegate方法時(shí),實(shí)際是調(diào)用自己的action方法。。
總之一句話:
這里子類(lèi)實(shí)現(xiàn)了父類(lèi)delegate中所期望的action方法
再來(lái)看看下面這段代碼:
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é)果如下:
super method
**************************************************
replace method
**************************************************
in extended class
super method
out extended class
**************************************************
in Provider.action
分別繼承父類(lèi)的方法,替換父類(lèi)的方法,擴(kuò)展了父類(lèi)的方法
Super類(lèi)定義了delegate方法并期待子類(lèi)實(shí)現(xiàn)action函數(shù),Provider子類(lèi)實(shí)現(xiàn)了action方法.
相信本文所述對(duì)大家Python程序設(shè)計(jì)的學(xué)習(xí)有一定的借鑒價(jià)值。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

