ChangeMyName
ChangeMyName

Reputation: 7418

OnInit and __init__ in wxPython

I am learning wxPython. In one of the examples, the code is like follows:

import wx

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


app=App()
app.MainLoop()

And I noticed that class App has no constructor but a function OnInit. As far as I know, Python classes are constructed with __init__ function.

So, is OnInit functions are for specific classes? Or it is another type of constructor?

Please forgive my ignorance since I am new to this. Thanks.

Upvotes: 6

Views: 6186

Answers (2)

falsetru
falsetru

Reputation: 369304

According to wx.App.__init__ documentation:

You should override OnInit to do applicaition initialization to ensure that the system, toolkit and wxWidgets are fully initialized.

-> OnInit method is only for classes that derive wx.App.

Upvotes: 5

Floggedhorse
Floggedhorse

Reputation: 694

Assuming you got the code from "wxPython in Action" book- good book would recommend,

It goes on to say (Im sure you have red this by now)...

Notice that we didn’t define an init()method for our application class. In Python, this means that the parent method, wx.App.init(), is automatically invoked on object creation. This is a good thing. If you define an init() method of your own, don’t forget to call the init()of the base class, like this:

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

If you forget to do so, wxPython won’t be initialized and your OnInit()method won’t get called.

Upvotes: 1

Related Questions