子类化Python类以继承超类的属性

Zek*_*oid 0 python inheritance

我试图从超类继承属性,但它们没有被正确初始化:

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

class OtherThing(Thing):
    def __init__(self):
        super(Thing, self).__init__()
        print self.attribute1
Run Code Online (Sandbox Code Playgroud)

这会引发错误,因为即使Thing.attribute1存在,attribute1也不是OtherThing的属性.我认为这是继承和扩展超类的正确方法.难道我做错了什么?我不想创建Thing的实例并使用它的属性,我需要它为了简单而继承它.

Chr*_*ian 9

作为参数,你必须给出类名(它被调用的地方)super():

super(OtherThing, self).__init__()
Run Code Online (Sandbox Code Playgroud)

根据Python文档:

... super可用于引用父类而不明确命名它们,从而使代码更易于维护.

所以你不应该给父类.也可以从Python文档中查看此示例:

class C(B):
    def method(self, arg):
        super(C, self).method(arg)
Run Code Online (Sandbox Code Playgroud)