functors
Tom Plunket
tomas at fancy.org
Tue Jul 1 21:25:18 EDT 2003
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. 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)
# I have also tried 'lambda: self.Callback'
self.done = False
def Callback(self):
print "success!"
self.done = True
def Update(self):
while not self.done:
self.countdown.Update()
if __name__ == "__main__":
SomeClass().Update()
***
I wouldn't mind creating a new class to wrap this up (that's what
I'd do in C++, and that class would have an operator() defined),
but I can't seem to discover how to make callable objects in
Python.
If there's a better way to do callbacks like I'm trying to do,
also that would be handy to know. :) I don't want to poll the
countdown object every time through the loop because it just
seems "dirty"... :)
thanks,
-tom!
More information about the Python-list
mailing list