function with a state

Andrew Koenig ark at acm.org
Sun Mar 6 16:25:11 CET 2005


"Xah Lee" <xah at xahlee.org> wrote in message 
news:1110096425.669042.11050 at o13g2000cwo.googlegroups.com...

> globe=0;
> def myFun():
>  globe=globe+1
>  return globe
>
> apparently it can't be done like that. I thought it can probably be
> done by prefixing the variable with some package context...

You can do this:

    globe=0
    def myFun():
        global globe
        globe=globe+1
        return globe

The question you should ask yourself, however, is why you want to do this. 
Do you really want to tie your function to a single global variable?  Are 
you sure you will never need more than one?

For example, the function you've written represents a counter.  Are you sure 
you will never need more than one such counter?





More information about the Python-list mailing list