python super()函數(shù)的基本使用
super主要來(lái)調(diào)用父類方法來(lái)顯示調(diào)用父類,在子類中,一般會(huì)定義與父類相同的屬性(數(shù)據(jù)屬性,方法),從而來(lái)實(shí)現(xiàn)子類特有的行為。也就是說(shuō),子類會(huì)繼承父類的所有的屬性和方法,子類也可以覆蓋父類同名的屬性和方法。
class Parent(object): Value = 'Hi, Parent value' def fun(self): print('This is from Parent') # 定義子類,繼承父類class Child(Parent): Value = 'Hi, Child value' def ffun(self): print('This is from Child') c = Child()c.fun()c.ffun()print(Child.Value) # 輸出結(jié)果# This is from Parent# This is from Child# Hi, Child value
但是,有時(shí)候可能需要在子類中訪問(wèn)父類的一些屬性,可以通過(guò)父類名直接訪問(wèn)父類的屬性,當(dāng)調(diào)用父類的方法是,需要將”self”顯示的傳遞進(jìn)去的方式。
class Parent(object): Value = 'Hi, Parent value' def fun(self): print('This is from Parent') class Child(Parent): Value = 'Hi, Child value' def fun(self): print('This is from Child') # 調(diào)用父類Parent的fun函數(shù)方法 Parent.fun(self) c = Child()c.fun() # 輸出結(jié)果# This is from Child# This is from Parent# 實(shí)例化子類Child的fun函數(shù)時(shí),首先會(huì)打印上條的語(yǔ)句,再次調(diào)用父類的fun函數(shù)方法
這種方式有一個(gè)不好的地方就是,需要經(jīng)父類名硬編碼到子類中,為了解決這個(gè)問(wèn)題,可以使用Python中的super關(guān)鍵字。
class Parent(object): Value = 'Hi, Parent value' def fun(self): print('This is from Parent') class Child(Parent): Value = 'Hi, Child value' def fun(self): print('This is from Child') # Parent.fun(self) # 相當(dāng)于用super的方法與上一調(diào)用父類的語(yǔ)句置換 super(Child, self).fun() c = Child()c.fun() # 輸出結(jié)果# This is from Child# This is from Parent# 實(shí)例化子類Child的fun函數(shù)時(shí),首先會(huì)打印上條的語(yǔ)句,再次調(diào)用父類的fun函數(shù)方法
以上就是python super()函數(shù)的基本使用的詳細(xì)內(nèi)容,更多關(guān)于python super()函數(shù)的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. .NET中l(wèi)ambda表達(dá)式合并問(wèn)題及解決方法2. JSP數(shù)據(jù)交互實(shí)現(xiàn)過(guò)程解析3. 淺談python出錯(cuò)時(shí)traceback的解讀4. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法5. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼6. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解7. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題8. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向9. 在Android中使用WebSocket實(shí)現(xiàn)消息通信的方法詳解10. Nginx+php配置文件及原理解析
