Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Re: functors (http://www.velocityreviews.com/forums/t319120-re-functors.html)

Bruno Desthuilliers 07-02-2003 11:37 AM

Re: functors
 
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



All times are GMT. The time now is 04:31 PM.

Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57