Static variables

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Jan 24 16:46:20 EST 2007


Florian Lindner a écrit :
> Hello,
> does python have static variables? I mean function-local variables that keep
> their state between invocations of the function.

Not directly. But there are ways to have similar behaviour:

1/ the mutable default argument hack:

def fun(arg, _hidden_state=[0]):
   _hidden_state[0] +=  arg
   return _hidden_static[0] * 2

2/ using OO:

class Fun(object):
   def __init__(self, static=0):
     self._state = static
   def __call__(self, arg):
     self._state += arg
     return self._state * 2

fun = Fun()


HTH



More information about the Python-list mailing list