Python子類構造函數調用super().__init__()用法說明,三種情況

Python子類構造函數調用super().__init__()用法說明
	</h1>
	<div class="clear"></div>
	<div class="postBody">

一、super的作用

1.如果子類(Puple)繼承父類(Person)不做初始化,那麼會自動繼承父類(Person)屬性name。
2.如果子類(Puple_Init)繼承父類(Person)做了初始化,且不調用super初始化父類構造函數,那麼子類(Puple_Init)不會自動繼承父類的屬性(name)。
3.如果子類(Puple_super)繼承父類(Person)做了初始化,且調用了super初始化了父類的構造函數,那麼子類(Puple_Super)也會繼承父類的(name)屬性。

複製代碼
class Father():
    def __init__(self,name = 'father'):
        self.name = name

class SonA(Father):
pass

class SonB(Father):
def init(self,age ):
self.age
= age

class SonC(Father):
def init(self,name,age ):

    self.age </span>=<span style="color: #000000;"> age
    self.name </span>=<span style="color: #000000;"> name
    super(SonC, self).</span><span style="color: #800080;">__init__</span><span style="color: #000000;">(name)

sona = SonA()
print(sona.name)

sonb = SonB(10)
print(sonb.name)

sonc = SonC(sonc,10)
print(sonc.name)

複製代碼
father

Traceback (most recent call last):
File "C:/Users/wiggin/PycharmProjects/AI/1簡單的神經網絡實現過程/test.py", line 24, in <module>
print(sonb.name)
AttributeError: 'SonB' object has no attribute 'name'

sonc

2.繼承中super的調用順序
繼承中super的調用順序是與MRO-C3的類方法查找順序一樣的
複製代碼
class A:
    def __init__(self):
        print('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()

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 = G()

複製代碼
G
E
B
F
C
D
A

 

標籤: python技巧
<div id="blog_post_info">
1
0
<div class="clear"></div>
<div id="post_next_prev">

<a href="https://www.cnblogs.com/wigginess/p/13048901.html" class="p_n_p_prefix">« </a> 上一篇:    <a href="https://www.cnblogs.com/wigginess/p/13048901.html" title="發佈於 2020-06-05 11:56">tensorflow2.0學習筆記第二章第四節</a>
<br>
<a href="https://www.cnblogs.com/wigginess/p/13062696.html" class="p_n_p_prefix">» </a> 下一篇:    <a href="https://www.cnblogs.com/wigginess/p/13062696.html" title="發佈於 2020-06-07 22:33">1.keras-構建基本簡單網絡實現線性迴歸</a>
posted @ 2020-06-05 14:49  wigginess  閱讀(26)  評論(0編輯  收藏
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章