python 父类构造函数,python 对于子类构造函数重写父类构造函数的了解
1、對子類實例化的時候,子類的構造函數會覆蓋父類的構造函數。super()相當于父類,所以在子類的構造函數中執行super(),就相當于執行了父類的構造函數
class Parent:
def __init__(self):
print('不想被覆蓋')
def add(self):
print('add')
class Son(Parent):
def __init__(self,a,b,c=10):
super().__init__()
print(a+b+c)
def add2(self):
print('add2')
son = Son(14,52)
son.add2()
son.add()
----------------------------
不想被覆蓋
76
add2
add
----------------------------
2、對子類實例化的時候,如果子類沒有顯式的寫構造函數,那么系統會自動給你添加構造函數并用super() 處理好。這個時候如果傳了參數,那么父類的構造函數就要接收傳入的參數,如下面的例子一樣。
class Parent:
def __init__(self,a,b):
print(a,b)
def add(self):
print('add')
class Son(Parent):
def add2(self):
print('add2')
son = Son(14,52)
son.add2()
son.add()
----------------------------
14 52
add2
add
----------------------------
標簽:__,add2,python,子類,self,add,print,構造函數
來源: https://www.cnblogs.com/huaniaoyuchong/p/13919917.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的python 父类构造函数,python 对于子类构造函数重写父类构造函数的了解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab 自动控制仿真,Matlab
- 下一篇: 远程连接oracle01017,连接Or