【问题标题】:Python Child object not accessing parent attributePython子对象不访问父属性
【发布时间】:2017-12-08 13:52:13
【问题描述】:

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

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子类无法访问它的父属性吗?

【问题讨论】:

    标签: python inheritance pyqt5 multiple-inheritance


    【解决方案1】:

    你得到的错误是因为你传递给super的参数。在 Python 2 中,它有 2 个参数:第一个参数是当前类 (Object2),第二个参数是当前实例 (self)。

    问题是您传递了 parent 类而不是 current 类。

    所以你想要:

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

    在 Python 3 中,不再需要将这些参数传递给 super。所以你会这样做:

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

    另见:

    https://stackoverflow.com/a/5066411/7220776

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2019-10-06
      • 2020-10-10
      相关资源
      最近更新 更多