2014-01-26 145 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()