久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

python super()函數(shù)的基本使用

瀏覽:155日期:2022-07-11 16:01:29

super主要來調用父類方法來顯示調用父類,在子類中,一般會定義與父類相同的屬性(數(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) # 輸出結果# This is from Parent# This is from Child# Hi, Child value

但是,有時候可能需要在子類中訪問父類的一些屬性,可以通過父類名直接訪問父類的屬性,當調用父類的方法是,需要將”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') # 調用父類Parent的fun函數(shù)方法 Parent.fun(self) c = Child()c.fun() # 輸出結果# This is from Child# This is from Parent# 實例化子類Child的fun函數(shù)時,首先會打印上條的語句,再次調用父類的fun函數(shù)方法

這種方式有一個不好的地方就是,需要經(jīng)父類名硬編碼到子類中,為了解決這個問題,可以使用Python中的super關鍵字。

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的方法與上一調用父類的語句置換 super(Child, self).fun() c = Child()c.fun() # 輸出結果# This is from Child# This is from Parent# 實例化子類Child的fun函數(shù)時,首先會打印上條的語句,再次調用父類的fun函數(shù)方法

以上就是python super()函數(shù)的基本使用的詳細內容,更多關于python super()函數(shù)的資料請關注好吧啦網(wǎng)其它相關文章!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 新干县| 钟山县| 青州市| 法库县| 沈丘县| 湖南省| 宁陕县| 安西县| 汉中市| 阳春市| 靖安县| 和林格尔县| 玉田县| 柞水县| 高州市| 增城市| 界首市| 昂仁县| 宜章县| 邢台县| 邛崃市| 新绛县| 富民县| 定州市| 乐安县| 松滋市| 深水埗区| 苍梧县| 三穗县| 太原市| 昆山市| 卢湾区| 兖州市| 新丰县| 宁明县| 兰西县| 竹北市| 海南省| 稷山县| 察隅县| 郓城县|