【问题标题】:What is the purpose of using python `super() `, inside `__init__ ` other than the inheritance?除了继承之外,在 __init__ 中使用 python `super()` 的目的是什么?
【发布时间】:2015-10-08 07:11:34
【问题描述】:

我在 Youtube 教程中发现了这个简单的程序,它使用 QtSide 模块和 python。基本上它所做的是将QLineEdit 连接到QTextBrowser。正如您在下面看到的,整个程序由单个类处理。我有用于多重继承的 super() 函数的基本概念。所以在这里,我不明白super(Form, self).__init__(parent) 语句的作用。在注释了产生以下错误消息的语句后,我尝试运行相同的程序。

错误:

Traceback (most recent call last):
  File "/home/dazz/Projects/PycharmProjects/FirstTutorial/a2_gui.py", line 35, in <module>
    form = Form()
  File "/home/dazz/Projects/PycharmProjects/FirstTutorial/a2_gui.py", line 17, in __init__
    self.setLayout(layout)
RuntimeError: '__init__' method of object's base class (Form) not called.

程序代码:

import sys
from PySide.QtCore import *
from PySide.QtGui import *


class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.browser = QTextBrowser()
        self.lineEdit = QLineEdit()


        layout = QVBoxLayout()
        layout.addWidget(self.browser)
        layout.addWidget(self.lineEdit)
        self.setLayout(layout)

        self.lineEdit.returnPressed.connect(self.update_ui)
        self.setWindowTitle('Calculate')

    def update_ui(self):
        try:
            text = self.lineEdit.text()
            self.browser.append('%s = %s' % (text, eval(text)))
            self.lineEdit.selectAll()

        except:
            self.browser.append('%s is invalid!' % text)

app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

这里,super()有什么用? 我找到了一个可能与此有关的question。但我不清楚。

【问题讨论】:

    标签: python pyside multiple-inheritance super


    【解决方案1】:

    super() 用于继承、多重或其他方式,以调用当前类中可能已被覆盖的方法。

    这里super() 用于调用为QDialog 或其父类定义的原始__init__ 方法。不调用原始方法可能会产生后果,因为原始方法确实有效,您不想在自己的 __init__ 方法中复制。

    super() 让多重继承更容易和更灵活地处理,但它不仅仅是多重继承。

    【讨论】:

    • 所以 setLayout(layout) 是 QDialog 对象的属性不是吗?
    • self.setLayout()QDialog 类的一个方法。
    【解决方案2】:

    正如您已经理解的那样,基本上,super() 用于继承。正如 Martjin 所提到的,当您发表评论时,在您的案例中出现的“后果”是需要在“QDialog”类中实现的初始化。

    因此,在这个子类中需要做的就是调用父类的 init。

    superinit 上的 stackoverflow 中已经有一篇不错的文章。

    super and init

    【讨论】:

      猜你喜欢
      • 2021-11-28
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      • 2018-11-06
      • 2021-11-23
      • 2012-01-07
      相关资源
      最近更新 更多