function with a state

Stephen Thorne stephen.thorne at gmail.com
Mon Mar 7 02:00:56 EST 2005


On Sun, 06 Mar 2005 09:44:41 +0100, Patrick Useldinger
<pu.news.001 at gmail.com> wrote:
> Xah Lee wrote:
> 
> > globe=0;
> > def myFun():
> >   globe=globe+1
> >   return globe
> 
> The short answer is to use the global statement:
> 
> globe=0
> def myFun():
>    global globe
>    globe=globe+1
>    return globe
> 
> more elegant is:
> 
> globe=0
> globe=myfun(globe)
> def myFun(var):
>    return var+1
> 
> and still more elegant is using classes and class attributes instead of
> global variables.

Or what about just using the function object directly?

def myFun():
  myFun.x += 1
  return myFun.x
myFun.x = 0

for test in range(10):
 assert myFun()+1 == myFun()
 assert myFun()*2+3 == myFun()+myFun()
 assert range(myFun(), myFun()+9) == [myFun() for x in range(10)]
 assert range(myFun()+2, myFun()+11) == [myFun() for x in range(10)]

:))

couldn't-help-feeding-the-troll-ly-y'rs.
Stephen Thorne.



More information about the Python-list mailing list