Bob Miller wrote:
> Those of you who were at the clinic last night know that I
> was asking for help on a weird limitation of Python.
> 
> The problem:  Consider the function, foo(), in this C program.
> 
>       #include <stdio.h>
> 
>       int foo()
>       {
>           static int n = 0;
>           return ++n;
>       }
> 
>       main()
>       {
>           int n1 = foo();
>           int n2 = foo();
>           printf("%d %d\n", n1, n2);
>           return 0;
>       }
> 
> It keeps state around between calls, but does not have extra names in
> any nonlocal namespaces.
> 
> How would you write a function in Python that does the same?
> (Note, I don't want a solution that only returns successive numbers.
> I might use this to return successive lines of a file or calculate
> successive permutations of a sequence or whatever.)
> 

I don't know offhand, but I would look at generators in python 2.x .
I haven't had to use them yet so I'm not sure of the details, but
I believe they offer the functionality you're looking for.

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)
        

                                        J. Toman

_______________________________________________
Eug-LUG mailing list
[EMAIL PROTECTED]
http://mailman.efn.org/cgi-bin/listinfo/eug-lug

Reply via email to