搜尋
首頁後端開發Python教學Python如何使用super()函數的__init__()方法?

super().__ init__ ()有什麼用?

super().__init__() 、 super(B,self).__init__()

1、分別理解super()和__ init __()

#1.1、super()

Python如何使用super()函數的__init__()方法?

需要注意的是python2、3的super写法稍有不同。
#1.2、 __ init __()

__init__() 是python中的建構函數,在建立物件的時"自動呼叫"。

Python如何使用super()函數的__init__()方法?

定义类时可以不写init方法,系统会默认创建,
你也可以写一个,让你的类在创建时完成一些“动作”。
1.3、super(). __ init __()

如果子類別B和父類別A,都寫了init方法,
那麼A的init方法就會被B覆蓋。想呼叫A的init方法要用super去呼叫。

Python如何使用super()函數的__init__()方法?

當然,在B內部,除了用super呼叫父類別的方法,也可以用父類別名稱調用,範例:

class B(A):
    def __init__(self):
        A.__init__(self)
        print("B init")
1.3.1 、關於「覆蓋」的疑問

有人可能會誤解「覆蓋」的意思,認為「覆蓋」了就是沒有,為什麼還能透過super呼叫?
覆蓋了並不是沒有了,A的方法終都還在,但需要在B內部用super呼叫。

例:
A里写了一个方法hi(), B继承自A, B里也写了一个方法hi()。
B的对象在外部调用hi(), 就只能调用B里面写的这个hi()。
想通过B调用A的hi(),只能在B内部用super().hi()调用。
class A:
    def hi(self):
        print("A hi")

class B(A):
    def hello(self):
        print("B hello")
        
b = B()
b.hi()       # B里没有写hi(),这里调用的是继承自A的hi()

------------------------------------------------------------------
class A:
    def hi(self):
        print("A hi")

class B(A):
    def hi(self):
        print("B hi")
        
b = B()
b.hi()    # 这里调用的就是B自己的hi()
------------------------------------------------------------------
class A:
    def hi(self):
        print("A hi")

class B(A):
    def hi(self):
        super().hi()         # 通过super调用父类A的hi()
        print("B hi")
        
b = B()
b.hi()    # 这里调用的就是B里面的hi()

2、super() 在python2、3中的區別

Python3.x 和Python2.x 的一個區別: Python 3 可以使用直接使用super().xxx 來取代super( Class, self).xxx :

例:
python3 直接寫成: super().__init__()
python2 必須寫成:super(本類別名稱,self).__init__( )

 Python3.x 實例:

class A:
     def add(self, x):
         y = x+1
         print(y)
class B(A):
    def add(self, x):
        super().add(x)
b = B()
b.add(2)  # 3

Python2.x 實例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class A(object):   # Python2.x 记得继承 object
    def add(self, x):
         y = x+1
         print(y)
class B(A):
    def add(self, x):
        super(B, self).add(x)
b = B()
b.add(2)  # 3

3、關於繼承順序

#最底層:先寫一個父類別A

class A:
    def __init__(self):
        print('A')

第二層:讓B、C、D 繼承自A

class B(A):
    def __init__(self):
        print('B')
        super().__init__()

class C(A):
    def __init__(self):
        print('C')
        super().__init__()

class D(A):
    def __init__(self):
        print('D')
        super().__init__()

第三層: E、F、G 繼承

class E(B, C):
    def __init__(self):
        print('E')
        super().__init__()

class F(C, D):
    def __init__(self):
        print('F')
        super().__init__()

class G(E, F):
    def __init__(self):
        print('G')
        super().__init__()

看看G的繼承順序

Python如何使用super()函數的__init__()方法?

Python如何使用super()函數的__init__()方法?

我們發現G繼承自E, F是並列的,初始化的時候不會先把E初始化完畢才初始化F。

4、從多個實例中對比super(python3)

下面是三種不同的繼承、調用,對比他們的區別,搞清楚super().__init__()的用途。

4.1、實例

Python如何使用super()函數的__init__()方法?

#子類別名稱 繼承內容
Puple 繼承所有
Puple_Init 繼承,但覆寫了init方法

Python如何使用super()函數的__init__()方法?

Python如何使用super()函數的__init__()方法?

################### ###Puple_Super######繼承,但覆寫了init方法,並在init裡面加入了super().__init__()############### 4.2、執行結果與比較###############4.3、完整程式碼############

以上是Python如何使用super()函數的__init__()方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:亿速云。如有侵權,請聯絡admin@php.cn刪除
在Python陣列上可以執行哪些常見操作?在Python陣列上可以執行哪些常見操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些類型的應用程序中,Numpy數組常用?在哪些類型的應用程序中,Numpy數組常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什麼時候選擇在Python中的列表上使用數組?您什麼時候選擇在Python中的列表上使用數組?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomoGeneData,performance-Caliticalcode,orinterfacingwithccode.1)同質性data:arraysSaveMemorywithTypedElements.2)績效code-performance-calitialcode-calliginal-clitical-clitical-calligation-Critical-Code:Arraysofferferbetterperbetterperperformanceformanceformancefornallancefornalumericalical.3)

所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactsperformance.2)listssdonotguaranteeconecontanttanttanttanttanttanttanttanttanttimecomplecomecomplecomecomecomecomecomecomplecomectacccesslectaccesslecrectaccesslerikearraysodo。

您如何在python列表中訪問元素?您如何在python列表中訪問元素?Apr 26, 2025 am 12:03 AM

toAccesselementsInapythonlist,useIndIndexing,負索引,切片,口頭化。 1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Python的科學計算中如何使用陣列?Python的科學計算中如何使用陣列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何處理同一系統上的不同Python版本?您如何處理同一系統上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

與標準Python陣列相比,使用Numpy數組的一些優點是什麼?與標準Python陣列相比,使用Numpy數組的一些優點是什麼?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具