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

