Perl-Python Tutorial: Function With a State

2005-03-09

Is it possible in Python to create a function that maintains a variable value? Something like this (which doesn't work):

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

Several people on comp.lang.python forum have given answers. The answers are paged below:

The simplest is to precede the setting of global variables by “global” keyword.

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

myFun();myFun();myFun()
print globe

The “global” keyword tells python that the variable you are using is in the global context. The Python doc is stilted with academicism. Here's its incomprehensible formalities on global, and it is the only place where it is talked about: http://python.org/doc/ref/global.html

Another way is to use a list instead of a variable.

globe= [ 0 ]
def myFun():
    globe[0]= globe[0] + 1
    return globe[0]

myFun();myFun();myFun()
print globe[0]

Another way is using the OOP facilities built-in in Python.

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

myFun();myFun();myFun()
print myFun.x

See also:


Page created: 2005-03.
© 2005 by Xah Lee.
Xah Signet