2014-01-26 64 views
0

我試圖繼承一個超類屬性的超類的屬性,但他們沒有被正確初始化:子類Python類繼承

class Thing(object): 
    def __init__(self): 
     self.attribute1 = "attribute1" 

class OtherThing(Thing): 
    def __init__(self): 
     super(Thing, self).__init__() 
     print self.attribute1 

這將引發一個錯誤,因爲ATTRIBUTE1不是一個屬性OtherThing,即使Thing.attribute1存在。我認爲這是繼承和擴展超類的正確方法。難道我做錯了什麼?我不想創建一個Thing的實例並使用它的屬性,爲了簡單起見,我需要它來繼承它。

+4

你想'超(OtherThing,個體經營).__的init __()' –

回答

8

你必須給,如argument,類名(它被調用),以super()

super(OtherThing, self).__init__() 

根據Python docs

... super可以用來參考母類,而不將它們命名爲 明確,從而使代碼更易於維護。

所以你不應該給父類。 從Python docs太見這個例子:

class C(B): 
    def method(self, arg): 
     super(C, self).method(arg) 
+1

璀璨!謝謝! – ZekeDroid

2

Python3讓一切變得簡單:

#!/usr/local/cpython-3.3/bin/python 

class Thing(object): 
    def __init__(self): 
     self.attribute1 = "attribute1" 

class OtherThing(Thing): 
    def __init__(self): 
     #super(Thing, self).__init__() 
     super().__init__() 
     print(self.attribute1) 

def main(): 
    otherthing = OtherThing() 

main()