Construct class from superclass instance

风流意气都作罢 提交于 2019-12-24 11:44:56

问题


So you have some function, say Gtk.Builder.get_object(), which returns some widget. In our case a Gtk.Window().

I have a subclass of Gtk.Window() which adds some signal handlers.

class Window(Gtk.Window):

Is it possible to use the widget returned by Gtk.Builder.get_object() to construct Window()? I think it should be using __new__() or something, but I can't figure it out.


回答1:


I think using __new__ is exactly what you want to be doing. If you can set the __class__ attribute of the superclass instance you're getting to the subclass, you should be all set.

Here's what I think you need:

class Window(Gtk.Window):
    def __new__(cls, *args, **kwargs):
        self = Gtk.Builder.get_object()
        self.__class__ = cls
        return self

Python should detect that the value that was created by __new__ is an instance of the class (thanks to the __class__ value), then it will call __init__ and other methods as appropriate.



来源:https://stackoverflow.com/questions/15330755/construct-class-from-superclass-instance

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