简体   繁体   English

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

[英]Subclassing a Python class to inherit attributes of super class

I'm trying to inherit attributes from a super class but they are not being initialized correctly: 我正在尝试从超类继承属性,但它们未正确初始化:

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

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

This throws an error since attribute1 is not an attribute of OtherThing, even though Thing.attribute1 exists. 这会引发错误,因为即使Thing.attribute1存在,attribute1也不是OtherThing的属性。 I thought this was the correct way to inherit and extend a super class. 我认为这是继承和扩展超类的正确方法。 Am I doing something wrong? 难道我做错了什么? I don't want to create an instance of Thing and use its attributes, I need it to inherit this for simplicity. 我不想创建Thing的实例并使用其属性,为了简单起见,我需要它来继承它。

You have to give, as argument , the class name (where it is being called) to super() : 您必须将类名(被调用的地方)作为参数传递给super()

super(OtherThing, self).__init__()

According to Python docs : 根据Python文档

... super can be used to refer to parent classes without naming them explicitly , thus making the code more maintainable. ... super可以用于引用父类, 而无需显式命名它们 ,从而使代码更具可维护性。

so you are not supposed to give the parent class . 所以你不应该给父母上课 See this example from Python docs too: 也可以从Python文档中查看以下示例:

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

Python3 makes this easy: 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM