python super()函數(shù)的基本使用
super主要來調(diào)用父類方法來顯示調(diào)用父類,在子類中,一般會定義與父類相同的屬性(數(shù)據(jù)屬性,方法),從而來實現(xiàn)子類特有的行為。也就是說,子類會繼承父類的所有的屬性和方法,子類也可以覆蓋父類同名的屬性和方法。
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
但是,有時候可能需要在子類中訪問父類的一些屬性,可以通過父類名直接訪問父類的屬性,當調(diào)用父類的方法是,需要將”self”顯示的傳遞進去的方式。
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 # 實例化子類Child的fun函數(shù)時,首先會打印上條的語句,再次調(diào)用父類的fun函數(shù)方法
這種方式有一個不好的地方就是,需要經(jīng)父類名硬編碼到子類中,為了解決這個問題,可以使用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) # 相當于用super的方法與上一調(diào)用父類的語句置換 super(Child, self).fun() c = Child() c.fun() # 輸出結(jié)果 # This is from Child # This is from Parent # 實例化子類Child的fun函數(shù)時,首先會打印上條的語句,再次調(diào)用父類的fun函數(shù)方法
以上就是python super()函數(shù)的基本使用的詳細內(nèi)容,更多關(guān)于python super()函數(shù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
matplotlib繪制鼠標的十字光標的實現(xiàn)(內(nèi)置方式)
這篇文章主要介紹了matplotlib繪制鼠標的十字光標的實現(xiàn)(內(nèi)置方式),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01對django中render()與render_to_response()的區(qū)別詳解
今天小編就為大家分享一篇對django中render()與render_to_response()的區(qū)別詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10詳解Django中的ifequal和ifnotequal標簽使用
這篇文章主要介紹了詳解Django中的ifequal和ifnotequal標簽使用,Django是重多高人氣Python框架中最為著名的一個,需要的朋友可以參考下2015-07-07Python采集天天基金數(shù)據(jù)掌握最新基金動向
這篇文章主要介紹了Python采集天天基金數(shù)據(jù)掌握最新基金動向,本次案例實現(xiàn)流程為發(fā)送請求、獲取數(shù)據(jù)、解析數(shù)據(jù)、多頁爬取、保存數(shù)據(jù),接下來來看看具體的操作過程吧2022-01-01django執(zhí)行數(shù)據(jù)庫查詢之后實現(xiàn)返回的結(jié)果集轉(zhuǎn)json
這篇文章主要介紹了django執(zhí)行數(shù)據(jù)庫查詢之后實現(xiàn)返回的結(jié)果集轉(zhuǎn)json,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03