python面向對象的主要好處就是代碼的重用,實現這一特點通過繼承,繼承創建的新類成為子類,被繼承的類稱為父類。
如果在子類中需要父類的構造方法就需要顯示的調用父類的構造方法,在調用基類的方法時,需要加上基類的類名前綴,且需要帶上self參數變量。
下面我們開始來講解繼承和多繼承
首先我們創建兩個類,
父類:Father類子類:Child
父類中屬性為money,和一個方法play(),輸出
fatherplaywithme
來表示繼承父類的方法。在繼承的時候我們需要在子類中導入父類
父類的代碼如下:
classFather(object):
def__init__(self,money):
self.money=money
print('money',money)
defplay(self):
print('fatherplaywithme')
因為孩子是繼承父親的,所以孩子類中也有money屬性。所以我們直接用child來繼承Father類。
child代碼如下:
fromFatherimportFather
classChild(Mother,Father):
def__init__(self,money):
Father.__init__(self,money)
這個時候我們的child類就繼承來自父類的屬性money而且我們還繼承了來自父類的方法play(),我們可以直接調用。
來驗證一下
fromChildimportChild
defmain():
c=Child(100)
c.play()
if__name__=='__main__':
main()
我們從輸出臺可以得到money100fatherplaywithme
多繼承
單繼承有時候可能滿足不了我們所需的所以我們就會遇到多繼承,這個同樣能夠展示出代碼的重用。
同樣是上邊的例子,child不僅僅是繼承來自父親,還繼承來自母親。所以我們創建mother類
classMother(object):
def__init__(self,face):
self.face=face
print('face',face)
defplay(self):
print('mothergoshoppingwithme')
mothe類創建的屬性為face,其次我們還定義的一個相同的方法play是為了展示多繼承中如果有相同的函數會調用哪個。
然后我們重寫一下child類
fromFatherimportFather
fromMotherimportMother
classChild(Mother,Father):
def__init__(self,money,face):
Father.__init__(self,money)
Mother.__init__(self,face)
以上內容為大家介紹了Python培訓之可以多繼承嗎,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。