function with a state

Dan Bishop danb_83 at yahoo.com
Wed Mar 9 07:41:03 EST 2005


and-google at doxdesk.com wrote:
> Xah Lee <xah at xahlee.org> wrote:
>
> > is it possible in Python to create a function that maintains a
> > variable value?
>
> Yes. There's no concept of a 'static' function variable as such, but
> there are many other ways to achieve the same thing.
>
> > globe=0;
> > def myFun():
> >   globe=globe+1
> >   return globe
>
> [snip]
>
> For more complicated cases, it might be better to be explicit and use
> objects:
>
>   class Counter:
>     def __init__(self):
>       self.globe= 0
>     def count(self):
>       self.globe+= 1
>       return self.globe
>
>   myFun= Counter().count

You can also use generators.

>>> def myGenerator():
...    var = 0
...    while True:
...       var += 1
...       yield var
...
>>> myFun = myGenerator().next
>>> myFun()
1
>>> myFun()
2
>>> myFun()
3
>>> myFun()
4




More information about the Python-list mailing list