toman wrote:
> I don't know offhand, but I would look at generators in python 2.x .
Ralph suggested generators too. A generator would work, but the
generator function doesn't do what I want itself, it returns an object
that does what I want. I.e., instead of saying,
print foo(), foo()
I'd say
foo_gen = foo().next
print foo_gen(), foo_gen()
(Here's the generator version of foo.)
from __future__ import generators
def foo():
n = 0
while 1:
n += 1
yield n
> Hmm, thinking about this for a second, what's wrong with:
>
> class bar :
> def __init__(self) :
> self.n = 0
>
> def __call__(self) :
> self.n = self.n +1
> return self.n
>
>
> if __name__== '__main__' :
> foo = bar()
> n1 = foo()
> n2 = foo()
> print "%d %d\n"%( n1, n2)
Same thing. "foo" returns an object that does what we want, it's
not the object itself.
At this point it's mostly academic. There are several ways to get the
desired functionality, and each is only slightly ugly. But it seems
weird that it isn't straightforward in Python.
What about Perl?
use strict;
sub foo() {
our $n;
return ++$n; # autovivifies $n.
}
printf "%d %d\n", foo(), foo();
Perl had to introduce a new keyword to make this work, "our", which
was new in 5.6, I think. Hunh.
It's interesting to watch the evolution of Perl and Python. They're
really the same language, except that (a) Perl has a 5-8 year head
start, and (b) the Python people refuse to accept anythying ugly into
the language.
--
Bob Miller K<bob>
kbobsoft software consulting
http://kbobsoft.com [EMAIL PROTECTED]
_______________________________________________
Eug-LUG mailing list
[EMAIL PROTECTED]
http://mailman.efn.org/cgi-bin/listinfo/eug-lug