Python Child object 未访问 parent 属性

Python Child object not accessing parent attribute

所以我正在用 PyQt5 编写程序并使用 QObject class。这是基本程序。

class Object(QObject):

    def __init__(self, parent=None):
        super(Object, self).__init__(parent)
        self.field = []


class Object2(Object):

    def __init__(self):
        super(Object, self).__init__()
        self.field.append(1)

if __name__ == '__main__':
    o = Object2()

但是我收到这个错误:

AttributeError: 'Object2' object has no attribute 'field'

我似乎找不到问题的原因。是不是 python child class 无法访问它的 parents 属性?

您收到的错误是因为您传递给 super 的参数。在 Python2 中,它有两个参数:第一个参数是当前 class (Object2),第二个参数是当前实例 (self).

问题是你传递了 parent class 而不是 current class.

所以你想要:

class Object2(Object):
    def __init__(self):
        super(Object2, self).__init__() # Current class: Object2
        self.field.append(1)

在Python3中,不再需要将这些参数传递给super。所以你只需要做:

class Object2(Object):
    def __init__(self):
        super().__init__()
        self.field.append(1)

另请参阅:

Python 2 个文档:https://docs.python.org/2/library/functions.html#super

Python 3 个文档:https://docs.python.org/3/library/functions.html#super