本文介绍了从超类实例构造类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以你有一些功能,说 Gtk.Builder.get_object(),它返回一些小部件。在我们的例子中有一个 Gtk.Window()



.Window()其中添加了一些信号处理程序。

  class Window(Gtk.Window):

是否可以使用 Gtk.Builder.get_object 构建 Window()?我认为应该使用 __ new __()或者什么,但我不能弄清楚。

我想使用 __ new __ 正是你想做的。如果你可以设置你的子类的超类实例的 __ class __ 属性,你应该全部设置。



这是我认为你需要:

  class Window(Gtk.Window):
def __new __ ,* args,** kwargs):
self = Gtk.Builder.get_object()
self .__ class__ = cls
return self
pre>

Python应该检测到由 __ new __ 创建的值是类的一个实例 __ class __ value),那么它会调用 __ init __ 和其他方法。


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.

解决方案

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.

这篇关于从超类实例构造类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 00:52