Static Variables in Python?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Jul 31 16:30:06 EDT 2006


Roel Schroeven a écrit :
> Michael Yanowitz schreef:
> 
>>   Is it possible to have a static variable in Python - a local 
>> variable in a function that retains its value.
>>
(snip)
> 
> You could do it by defining static_bits as a keyword parameter with a 
> default value:
> 
(snip)
> It might be a better idea to use a class for this though:
> 
(snip)

Last solution being to use a closure:

def make_bits():
   bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
   def set_bit(bit_index, bit_value):
     bits[bit_index] = bit_values
   def get_bits():
     # returns a copy so we don't overwrite
     return bits[:]
   return set_bit, get_bits

set_bit, get_bits = make_bits()

But the better solution is probably to make it a class.



More information about the Python-list mailing list