Static Variables in Python?
Carsten Haese
carsten at uniqsys.com
Mon Jul 31 15:52:25 EDT 2006
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.
More information about the Python-list
mailing list