一些环境基础知识
Python版本:3.4.2
操作系统:Windows 8.1
到目前为止的搜索,我怀疑这另一个问题 https://stackoverflow.com/questions/12280371/python-runtimeerror-super-class-init-of-s-was-never-called与我手头的问题有关,但我不确定我如何复制足够多的相同条件——可能是我缺乏深入的Python知识。
重现问题的简化代码:
基类
from PySide.QtGui import *
class Interface(QWidget):
'''
Wrapper base class for GUI input QWidgets:
- buttons
- text fields
- checkboxes
- line edit
- dropdown menu (combo box)
'''
def __init__(self, parent, name, title_txt=None, qt_obj=None,
update_log_method=None):
print('Interface base class constructor has been called.') #DEBUG
self._parent = parent
self.title = None
self.name = name #also text that appears on component
self.qt_obj = qt_obj
self.inheritted_log_method = update_log_method
# don't want to create an empty text QLabel, or one with
# the text reading "None".
if title_txt:
self.title = QLabel(text=title_txt, parent=parent)
print('Interface base class constructor has been completed.') #DEBUG
def get_name(self):
return self.name
def update_log(self, message, level="INFO"):
''' '''
self.inheritted_log_method(message, level)
继承类
class IFPushButton(Interface):
''' '''
def __init__(self, name, parent, icon=None, update_log_method=None):
''' '''
# print('\n\nCHECKPOINT: pre IFPushButton super()\n\n') #DEBUG
super(IFPushButton, self).__init__(
parent=parent,
name=name,
qt_obj=QPushButton(icon, name, parent),
update_log_method=update_log_method)
self.behaviors = {}
self.qt_obj.clicked.connect(self.activate)
一切开始的东西
if __name__ == '__main__':
# setup
import sys
app = QApplication(sys.argv)
qmw = QMainWindow()
qcw = QWidget() #central widget
qcl = QVBoxLayout(qcw) #central layout
# experimental
name = 'named button'
ifpb = IFPushButton(name=name, parent=None, icon=None, update_log_method=None)
print("as long a I don't touch the ifpb instance, everything seems to be okay.")
print("...but the second I do...")
qcl.addWidget(ifpb)
self.show()
print("name of created push button:", ifpb.get_name())
# proper teardown
sys.exit(app.exec_())
我在一个模块中运行这一切,interface.py
,当我运行它时......
C:\Path\To\Module> python interface.py
Interface base class constructor has been called.
Interface base class constructor has been completed.
as long a I don't touch the ifpb instance, everything seems to be okay.
...but the second I do...
Traceback (most recent call last):
File "c_interface.py", line 167, in <module>
qcl.addWidget(ifpb)
RuntimeError: '__init__' method of object's base class (IFPushButton) not called.
让我困惑的部分是基类中的 print 语句如何,Intefrace
,显然在打印时被调用 - 但它仍然引发一个运行时错误,说它尚未初始化,当然无法创建应用程序窗口。我在 stackoverflow 上找到的大多数相关消息都与人们使用 super() 方法错误地初始化有关 - 但我已经五次检查了我的 super 初始化,我看到的所有内容都告诉我它应该可以工作,但有例外我上面链接的内容。
如果我能更多地了解为什么会发生这种情况,我希望我能找到一种方法来解决它。非常感谢任何帮助——提前致谢!
与此同时,我将尝试找出如何无意中深度复制 C++ 对象......
EDIT:将 url 包含在其他堆栈溢出帖子的链接中。