Static Variables in Python?
tac-tics
tactics40 at gmail.com
Mon Jul 31 15:50:54 EDT 2006
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.
If you declare bits in set_bit() as "global bits = ...", it will create
it as a global variable without you having to declare it outside of the
function. Just be careful about name conflicts.
More information about the Python-list
mailing list