function with a state
and-google at doxdesk.com
and-google at doxdesk.com
Sun Mar 6 03:50:17 EST 2005
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
This would work except that you have to tell it explicitly that you're
working with a global, otherwise Python sees the "globe=" and decides
you want 'globe' be a local variable.
globe= 0
def myFun():
global globe
globe= globe+1
return globe
Alternatively, wrap the value in a mutable type so you don't have to do
an assignment (and can use it in nested scopes):
globe= [ 0 ]
def myFun():
globe[0]+= 1
return globe[0]
A hack you can use to hide statics from code outside the function is to
abuse the fact that default parameters are calcuated at define-time:
def myFun(globe= [ 0 ]):
globe[0]+= 1
return globe[0]
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
--
Andrew Clover
mailto:and at doxdesk.com
http://www.doxdesk.com/
More information about the Python-list
mailing list