2011-10-02 21 views
15

答:的Python:超級__init __()與__init __(個體經營)

super(BasicElement, self).__init__() 

B:

super(BasicElement, self).__init__(self) 

是什麼A和B之間有什麼區別?我運行的大多數示例都使用A,但是我遇到了A不調用父__init__函數但B是的問題。爲什麼會這樣呢?哪些應該使用,哪些情況下?

+1

顯示其中'B'工作的代碼。 「'A'沒有調用」是什麼意思?你有錯誤嗎?怎麼了? 'A .__ init__'是否帶有'self'以外的參數? – agf

回答

23

你不應該需要做第二種形式,除非不知何故BasicElement類的__init__接受一個參數。

class A(object): 
    def __init__(self): 
     print "Inside class A init" 

class B(A): 
    def __init__(self): 
     super(B, self).__init__() 
     print "Inside class B init" 

>>> b = B() 
Inside class A init 
Inside class B init 

或與需要初始化參數類:

class A(object): 
    def __init__(self, arg): 
     print "Inside class A init. arg =", arg 

class B(A): 
    def __init__(self): 
     super(B, self).__init__("foo") 
     print "Inside class B init" 

>>> b = B() 
Inside class A init. arg = foo 
Inside class B init  
+5

這個結構的重要性在於超類A必須從對象中明確派生。只要聲明'class A:'就會在調用super init調用時引發異常'TypeError:must be type,not classobj'。 – parvus

+0

A類必須從對象派生!!!! A類必須派生自對象!!!!類A必須派生自對象!重複三次通知。 – bourneli

相關問題