functors
Bruno Desthuilliers
bdesth.nospam at removeme.free.fr
Wed Jul 2 07:37:36 EDT 2003
Tom Plunket wrote:
> How can I create a functor object in Python?
>
> What I want (being a C++ coder <g>), is to be able to create an
> object that I is callable.
__call__ is your friend.
> The following is my attempt, but it
> doesn't work:
>
> class Countdown:
> def __init__(self):
> self.callback = None
>
> def SetCallback(self, time, callback):
> self.callback = callback
> self.timeRemaining = time
>
> def Update(self):
> if self.callback is not None:
> self.timeRemaining -= 1
> if self.timeRemaining <= 0:
> print "Callback fired."
> self.callback()
> self.callback = None
>
> class SomeClass:
> def __init__(self):
> self.countdown = Countdown()
> self.countdown.SetCallback(30, lambda s=self: s.Callback)
This is not the same problem as making an object (ie a class instance)
callable. Here you just want to use an instance object as callback function.
Functions in Python are first-class objects, so you don't need this
lambda stuff. This should work (I tried a simplified version...):
self.countdown.SetCallback(30, self.Callback)
HTH
Bruno
More information about the Python-list
mailing list