Static Variables in Python?

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Mon Jul 31 15:49:48 EDT 2006


Michael Yanowitz schreef:
>   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.

You could do it by defining static_bits as a keyword parameter with a 
default value:

 >>> 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]):
	static_bits[bit_index] = bit_value
	return static_bits

 >>> set_bit(2, 1)
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 >>> set_bit(3, 1)
[0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 >>> set_bit(2, 0)
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

It might be a better idea to use a class for this though:

 >>> class Bits(object):
	def __init__(self):
		self.bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
	def set(self, index, value):
		self.bits[index] = value
		return self.bits

	
 >>> bits = Bits()
 >>> bits.set(2, 1)
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 >>> bits.set(3, 1)
[0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 >>> bits.set(2, 0)
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

When using a class, you can have different lists of bits independently 
of each other in a program. And you can define other operations on the 
bits: you could for example create methods to set or clear all bits at 
once. With your approach, set_bit is the only function that has access 
to the bits so you can't easily create other operations.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven



More information about the Python-list mailing list