Python子类构造函数调用super().__init__()用法说明
一、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 = age self.name = name super(SonC, self).__init__(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