Python:使用decorator更改类类型并保留其方法

2024-06-26 18:00:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个类,它可以在不同的应用程序及其api中使用来创建ui。因此,我创建了一个名为的模块用户界面。本模块内有以下内容:

from PyQt4 import QtGui


def CreateGui(uiFile, parent=None):
    print "Ui build.."

def GetUiObject(uiClass):
    pUI = uiClass.PARENT
    class ParentUI(pUI):
        def __init__(self, uiFile):
            CreateGui(uiFile, self)
        def __call__(self, cls):
            for func in uiClass.__dict__:
                setattr(cls, func, uiClass.__dict__[func])
    return ParentUI

@GetUiObject
class UI(object):
    PARENT = QtGui.QMainWindow

    def __init__(self, uiFile):
        CreateGui(uiFile)

在应用程序使用的管道模块模块中:

^{pr2}$

但我得到了以下错误:

Ui build..
In Application
Traceback (most recent call last):
  File "C:/test/maxUi.py", line 13, in <module>
    A.CreateGui()
RuntimeError: super-class __init__() of type Tool_UI was never called

我错了什么?在

编辑:

cpburnz回答了代码出错的原因,但它仍然不起作用。 我想用另一个基址不同的类来替换这个类。我打开了一个新问题,对我的问题有了更好的描述,并尝试了不同的解决方案(How to rebase or dynamically replace a class with a different base class)。在


Tags: 模块buildself应用程序uiinitdefclass
1条回答
网友
1楼 · 发布于 2024-06-26 18:00:39

这看起来与Python: RuntimeError: super-class __init__() of %S was never called有关,但您的设置有点不同,所以我将推断以使其更清楚。在

Traceback (most recent call last):
  File "C:/test/maxUi.py", line 13, in <module>
    A.CreateGui()
RuntimeError: super-class __init__() of type Tool_UI was never called

这意味着在Tool_UI的类层次结构中,super(...).__init__(...) 没有被召唤。这似乎是由QObjectQWidget引起的。 查看在GetUiObject()中定义的类,没有调用super的init 即使父类pUIQWidget。你很可能需要补充 在那里调用super init:

^{pr2}$

相关问题 更多 >