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

ZekeDroid

我正在尝试从超类继承属性,但它们未正确初始化:

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

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

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

基督教

您必须将类名(被调用的地方)作为参数提供super()

super(OtherThing, self).__init__()

根据Python文档

...super可以用来引用父类而无需显式命名它们,从而使代码更具可维护性。

所以你不应该参加家长班也可以从Python文档中查看以下示例

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章