On Mon, 2006-07-31 at 15:21, Michael Yanowitz wrote: > Is it possible to have a static variable in Python - > a local variable in a function that retains its value. > > For example, suppose I have: > > def set_bit (bit_index, bit_value): > static bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] > bits [bit_index] = bit_value > > print "\tBit Array:" > int i > while (i < len(bits): > print bits[i], > print '\n' > > > I realize this can be implemented by making bits global, but can > this be done by making it private only internal to set_bit()? I don't > want bits to be reinitialized each time. It must retain the set values > for the next time it is called.
Python does not have static variables in the sense that C does. You can fake it in various ways, though. If I had to do it, I'd define a callable object instead of a function, along the lines of this: class BitSetter(object): def __init__(self): self.bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] def __call__(self, bit_index, bit_value): self.bits[bit_index] = bit_value # do something with self.bits here... print self.bits set_bit = BitSetter() Now you can call set_bit(...) as if it were a function, and it'll behave the way you want. Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list