Python: Change class type with decorator and keep it's methods

时光总嘲笑我的痴心妄想 提交于 2020-01-05 10:10:14

问题


I want to create a class which could be used inside different Applications and their APIs to create UIs. Therefor I created a module called ui.py. Inside this module is the following:

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)

Inside my pipeline module module, which is used by the application:

from ui import UI

UI.PARENT = QtGui.QWidget

class Tool_UI(UI):
    def __init__(self, uiFile):
        super(Tool_UI, self).__init__(uiFile)
        print "In Application"


app = QtGui.QApplication(sys.argv)
A = Tool_UI("C:/test/testUi.ui")
A.CreateGui()

But I get the following Error:

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

What do I wrong?

EDIT:

cpburnz answers why the code is erroring, but it is still not working. I want to replace the class with another one which has a different base. I opened a new question with a better description of my problem and different solutions I tried (How to rebase or dynamically replace a class with a different base class).


回答1:


This looks related to Python: RuntimeError: super-class __init__() of %S was never called but your setup is kind of different so I'll extrapolate to make it more clear.

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

This means somewhere in the class hierarchy for Tool_UI that super(...).__init__(...) is not being called. This appears to be raised by QObject or QWidget. Looking at the class defined in GetUiObject(), there is no call to the super's init even though the parent class pUI is QWidget. You most likely need to add a call to the super init there:

def GetUiObject(uiClass):
    pUI = uiClass.PARENT

    class ParentUI(pUI):

        def __init__(self, uiFile):
            super(ParentUI, self).__init__() # <-- Missing.
            CreateGui(uiFile, self)

        def __call__(self, cls):
            for func in uiClass.__dict__:
                setattr(cls, func, uiClass.__dict__[func])

    return ParentUI


来源:https://stackoverflow.com/questions/29368372/python-change-class-type-with-decorator-and-keep-its-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!