问题
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