static keyword

Ekki ekkilu at yahoo.com
Fri Apr 30 00:08:21 EDT 2004


nicksjacobson at yahoo.com (Nick Jacobson) wrote in message news:<f8097096.0404291403.400304ee at posting.google.com>...
> The bad news: I just hope I don't forget and call foo() instead of
> g.next().
> I would rather the command foo() by default call the next iteration,
> and, say, foo().reset() would recall the function from scratch.  But
> that's neither here nor there..

C++ functors (analogous to Python callables) do what you want and a
lot more. I am sure your problem does not need to get to this level,
but here is some food for thought. Notice the absence of
if-statements.

class F:
    def __call__(self):
        print "First pass"
        self.i = [10, 11]               # initialization
        self.first_call = self.__call__ # metaprogramming fun
        self.__call__ = self.call       # metaprogramming fun
        self()
    def call(self):
        self.i[0] += 1
        print self.i[0]
    def reset(self):
        self.__call__ = self.first_call # metaprogramming fun
f = F()

f()
f()

f.reset()
f()
f()

The full power of functors/callables only shows up when you combine
them with inheritance.

regards,

Hung Jung



More information about the Python-list mailing list