本文實例講述了Python面向對象程序設計之繼承與多繼承。分享給大家供大家參考,具體如下:
1. 繼承
在C++和Java中,使用繼承時,子類的構造函數會自動調用父類的構造函數,但在Python中,子類必須顯式的在__init__()
函數中再次調用父類中的__init__()
函數。如下例:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class Employee( object ): def __init__( self , name, salary = 0 ): self .name = name self .salary = salary def raisesalary( self , percent): self .salary = self .salary * ( 1 + percent) def work( self ): print self .name, "writes computer code" class Designer(Employee): def __init__( self , name): Employee.__init__( self , name, 5000 ) def work( self ): print self .name, "writes design document" |
子類Designer也可以使用super
來進行初始化。
1
2
3
4
5
|
class Designer(Employee): def __init__( self , name): super (Designer, self ).__init__(name, 5000 ) def work( self ): print self .name, "writes design document" |
2. 多繼承
在C++中,使用虛繼承來實現多繼承,以避免子類在繼承時多次調用基類的構造函數,而在Java中,則取消了多繼承,使用接口來達到多繼承的效果。在Python中的解決方案是MRO即Method Resolution Order,方法解析順序。主要是通過super
方法實現的。但如果用super
方法來解決多繼承問題,由于各個父類中的__init__()
函數中參數的數量可能不同,那應該怎么初始化呢?如下例。
1
2
3
4
5
6
7
8
9
10
|
class A( object ): def __init__( self , a): print a class B( object ): def __init__( self , a, b): print a + b class C(A, B): def __init__( self ): super (C, self ).__init__(?) c = C() |
則?處應該填幾個參數?
答案是1個參數,因為按照繼承的順序,A類中的構造需要1個參數初始化即可。即super
函數與父類的繼承順序有關,且初始化父類繼承順序中,最先有__init__()
方法的那個。
super
方法的使用仍在繼續探索中。。。
希望本文所述對大家Python程序設計有所幫助。
原文鏈接:https://blog.csdn.net/chenxiao_ji/article/details/50311597