</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
<div id="blog_post_info">
<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>