[Tutor] Callbacks in Python
Dave Angel
davea at ieee.org
Fri Aug 28 18:48:29 CEST 2009
Jramak wrote:
> Thanks everyone for your excellent insights. I think I understand the
> callback concept better.
> So, it is like passing a function as an argument to another function.
> I am interested in learning more about how callbacks can be applied in
> GUIs, using wxPython as an example. Would appreciate any insight.
>
> Thanks much
> Jramak
>
> On 8/27/09, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>> "Jramak" <jramak345 at gmail.com> wrote
>>
>>
>>> I'm confused by callbacks. I would really appreciate any introduction or
>>> help in understanding the concept of callbacks.
>>>
>> Callbacks are used in all sorts of different ways in programming
>> so it might help to undertand what exactly confuses you.
>>
>> Is it the whole concept of a callback?
>> Is it the idea of a function as an object?
>> Is it the use of callbacks?
>> In a GUI? In a networking framework like Twisted?
>>
>> Do you want to use someone elses callback mechanism
>> or do you want to create your own?
>>
>> The basic name comnes from the concept of calling
>> someone, asking them to do someting then call you back
>> when they are done. So you leave your number with them.
>> The number you leave is what they "call back".
>> In programming you call a function and at some critical
>> point that function calls you back on the function that
>> you passed in.
>>
>> def someFunction(value, callback)
>> result = pow(value,2)
>> callback(result)
>>
>> def myFunction()
>> v = 42
>> someFunction(v, myFunction_continue)
>>
>> def myFunction_contiinue(result)
>> print result
>>
>> myFunction()
>>
>> This was very useful before threading environments became
>> common as a way of simulating multi threading. Then when GUIs
>> came along it bacame a common way of associating functions
>> with widgets. And in networking we can associate network events
>> with functions in a similar way. In fact any kind of event driven
>> program is likely to use callbacks as a way of distributing control
>> depending on event type. The typical implementation will see the
>> event framework storing the callbacks in some kind of dictionary
>> keyed by event type.
>>
>> HTH,
>>
>>
>> --
>> Alan Gauld
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
>
If you have any sample code for wxPython, look for the Bind method. Generally used within widget code, it passes a reference to a method that should be called when some specific event happens to that widget. In the following line, if the widget gets resized (by the user dragging the edges of the window), my method OnSize() will be called.
self.Bind(wx.EVT_SIZE, self.OnSize)
DaveA
More information about the Tutor
mailing list