【问题标题】:OnInit and __init__ in wxPythonwxPython 中的 OnInit 和 __init__
【发布时间】:2014-01-27 21:24:20
【问题描述】:

我正在学习 wxPython。在其中一个示例中,代码如下:

import wx

class App(wx.App):    
    def OnInit(self):
        frame = wx.Frame(parent=None, title = 'bare')
        frame.Show()
        return True


app=App()
app.MainLoop()

我注意到App 类没有构造函数,但有一个函数OnInit。据我所知,Python 类是用__init__ 函数构造的。

那么,OnInit 函数是针对特定类的吗?还是另一种构造函数?

请原谅我的无知,因为我是新手。谢谢。

【问题讨论】:

    标签: python constructor wxpython


    【解决方案1】:

    根据wx.App.__init__ documentation

    您应该覆盖OnInit 来进行应用程序初始化,以确保 系统、工具包和 wxWidgets 已完全初始化。

    -> OnInit 方法仅适用于派生wx.App 的类。

    【讨论】:

      【解决方案2】:

      假设你从“wxPython in Action”一书中获得了代码——推荐的好书,

      它接着说(我确定你现在已经红了)......

      请注意,我们没有为我们的应用程序定义 init() 方法 班级。在 Python 中,这意味着父方法, wx.App.init(),在对象创建时自动调用。这 是一件好事。如果您定义了自己的 init() 方法,请不要 忘记调用基类的init(),像这样:

      class App(wx.App): 
           def __init__(self): 
               # Call the base class constructor. 
               wx.App.__init__(self) 
               # Do something here...
      

      如果您忘记这样做,wxPython 将不会被初始化并且您的 OnInit() 方法也不会被调用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-07
        • 1970-01-01
        • 2012-12-25
        相关资源
        最近更新 更多