问题描述
所以你有一些功能,说 Gtk.Builder.get_object()
,它返回一些小部件。在我们的例子中有一个 Gtk.Window()
。
.Window()其中添加了一些信号处理程序。
class Window(Gtk.Window):
是否可以使用 Gtk.Builder.get_object
构建 Window()
?我认为应该使用 __ new __()
或者什么,但我不能弄清楚。
我想使用 __ new __
正是你想做的。如果你可以设置你的子类的超类实例的 __ class __
属性,你应该全部设置。
这是我认为你需要:
class Window(Gtk.Window):
pre>
def __new __ ,* args,** kwargs):
self = Gtk.Builder.get_object()
self .__ class__ = cls
return self
Python应该检测到由
__ new __
创建的值是类的一个实例__ class __
value),那么它会调用__ init __
和其他方法。So you have some function, say
Gtk.Builder.get_object()
, which returns some widget. In our case aGtk.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 constructWindow()
? I think it should be using__new__()
or something, but I can't figure it out.解决方案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.这篇关于从超类实例构造类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!