Re: functors

Discussion in 'Python' started by Bruno Desthuilliers, Jul 2, 2003.

  1. 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
    Bruno Desthuilliers, Jul 2, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Paul MG
    Replies:
    2
    Views:
    383
    Dhruv
    Jul 3, 2003
  2. Rob Williscroft

    Re: Need help with generic functors....

    Rob Williscroft, Aug 17, 2003, in forum: C++
    Replies:
    3
    Views:
    341
    Gordon Scott
    Aug 18, 2003
  3. red floyd
    Replies:
    0
    Views:
    313
    red floyd
    Nov 13, 2003
  4. nsgi_2004

    functors

    nsgi_2004, Aug 12, 2004, in forum: C++
    Replies:
    2
    Views:
    455
    Karl Heinz Buchegger
    Aug 12, 2004
  5. Satish
    Replies:
    1
    Views:
    770
    David Hilsee
    Sep 10, 2004
Loading...

Share This Page