1、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()
GEBFCDA