本文實例講述了Python中super關鍵字用法。分享給大家供大家參考。具體分析如下:
在Python類的方法(method)中,要調用父類的某個方法,在Python 2.2以前,通常的寫法如代碼段1:
代碼段1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class A: def __init__( self ): print "enter A" print "leave A" class B(A): def __init__( self ): print "enter B" A.__init__( self ) print "leave B" >>> b = B() enter B enter A leave A leave B |
即,使用非綁定的類方法(用類名來引用的方法),并在參數列表中,引入待綁定的對象(self),從而達到調用父類的目的。
這樣做的缺點是,當一個子類的父類發生變化時(如類B的父類由A變為C時),必須遍歷整個類定義,把所有的通過非綁定的方法的類名全部替換過來,例如代碼段2,
代碼段2:
1
2
3
4
5
|
class B(C): # A --> C def __init__( self ): print "enter B" C.__init__( self ) # A --> C print "leave B" |
如果代碼簡單,這樣的改動或許還可以接受。但如果代碼量龐大,這樣的修改可能是災難性的。很容易導致修改錯誤的出現。
因此,自Python 2.2開始,Python添加了一個關鍵字super,來解決這個問題。下面是Python 2.3的官方文檔說明:
1
2
3
4
5
6
7
8
9
10
|
super ( type [, object - or - type ]) Return the superclass of type . If the second argument is omitted the super object returned is unbound. If the second argument is an object , isinstance (obj, type ) must be true. If the second argument is a type , issubclass (type2, type ) must be true. super () only works for new - style classes. A typical use for calling a cooperative superclass method is : class C(B): def meth( self , arg): super (C, self ).meth(arg) New in version 2.2 . |
從說明來看,可以把類B改寫如代碼段3:
代碼段3:
1
2
3
4
5
6
7
8
9
|
class A( object ): # A must be new-style class def __init__( self ): print "enter A" print "leave A" class B(C): # A --> C def __init__( self ): print "enter B" super (B, self ).__init__() print "leave B" |
嘗試執行上面同樣的代碼,結果一致,但修改的代碼只有一處,把代碼的維護量降到最低,是一個不錯的用法。因此在我們的開發過程中,super關鍵字被大量使用,而且一直表現良好。
1. super并不是一個函數,是一個類名,形如super(B, self)事實上調用了super類的初始化函數,產生了一個super對象;
2. super類的初始化函數并沒有做什么特殊的操作,只是簡單記錄了類類型和具體實例;
3. super(B, self).func的調用并不是用于調用當前類的父類的func函數;
4. Python的多繼承類是通過mro的方式來保證各個父類的函數被逐一調用,而且保證每個父類函數只調用一次(如果每個類都使用super);
5. 混用super類和非綁定的函數是一個危險行為,這可能導致應該調用的父類函數沒有調用或者一個父類函數被調用多次。
從super關鍵字的help我們也能看出來。
Help on class super in module __builtin__:
class super(object)
| super(type) -> unbound super object
| super(type, obj) -> bound super object; requires isinstance(obj, type)
| super(type, type2) -> bound super object; requires issubclass(type2, type)
| Typical use to call a cooperative superclass method:
| class C(B):
| def meth(self, arg):
| super(C, self).meth(arg)
|
| Methods defined here:
.......
從上面也能看出來,super是一個類,而且是__builtin__模塊中的。
從上面的描述來看,super主要是用于調用父類的方法。
那么,在2.2之前的方法也能調用。為啥非得用super呢?
這是因為super能夠阻止對父類方法的多次調用。
super,改變了父類搜索順序, 返回的是一個特殊的父類對象
看例子:
class A: pass class B(A): pass class C(A):pass class D(B, C): pass
這是4個類的基本關系。
假如不使用super,讓D的對象調用他們共有的一個方法,會2次調用A中這個方法。
希望本文所述對大家的Python程序設計有所幫助。