Static Variables in Python?

Cliff Wells cliff at develix.com
Tue Aug 1 15:43:04 EDT 2006


On Tue, 2006-08-01 at 07:37 -0400, Michael Yanowitz wrote:

> # ********* class BitsClass *****************************************  
> class BitsClass (object):
>     def __init__(self, num_bits):
>         self.bits=[]
>         for i in range(num_bits):
>             self.bits.append(0)
>     def set(self, bit_index, value):
> 		self.bits[bit_index] = value
> 		return self.bits
>     def get(self, bit_index):
>         if ((bit_index >= 0) and (bit_index < len(self.bits))):
>             return self.bits[bit_index]
>         else:
>             return scenario_globals.ERROR_
>     def display(self):
>         i = 0
>         while (i < len(self.bits)):
>             print self.bits[i],
>             i += 1
>         print '\n',
>         
> global the_bits
> the_bits = BitsClass(16)
> 
> # inside another function I have:
>     global the_bits
>     the_bits.set(index, value)
> 
>   but I get back:
> Traceback (most recent call last):
>    ...
>   File "scenario_sync.py", line 245, in get_discrete_data
>     the_bits.set(index, value)
> AttributeError: 'DiscreteBits' object has no attribute 'set'
> 
>   There is 
> 
>   I was also disappointed, I was hoping I could use BitsClass.print()
> instead of BitsClass.display().

>>> class BitsClass (object):
...     def __init__(self, num_bits):
...         self.bits=[]
...         for i in range(num_bits):
...             self.bits.append(0)
...     def set(self, bit_index, value):
...                 self.bits[bit_index] = value
...                 return self.bits
...     def get(self, bit_index):
...         if ((bit_index >= 0) and (bit_index < len(self.bits))):
...             return self.bits[bit_index]
...         else:
...             return scenario_globals.ERROR_
...     def display(self):
...         i = 0
...         while (i < len(self.bits)):
...             print self.bits[i],
...             i += 1
...         print '\n',
...
>>> the_bits = BitsClass(16)
>>> the_bits.set (4, 1)
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]


Works for me.  I'm not sure what 'DiscreteBits' in your error refers to.
Also, you don't need to explicitly declare global variables "global".

Regards,
Cliff

-- 




More information about the Python-list mailing list