D
David Coffin
I'd like to subclass int to support list access, treating the integer
as if it were a list of bits.
Assigning bits to particular indices involves changing the value of
the integer itself, but changing 'self' obviously just alters the
value of that local variable.
Is there some way for me to change the value of the BitSequence
object itself? I've also tried wrapping and delegating using
__getattr__, but I couldn't figure out how to handle in-place methods.
Thanks for your help,
David Coffin
class BitSequence(int):
"""An integer emulating a sequence of bits, subclassing int."""
def __new__(cls, value, length=32):
inst = super(BitSequence,cls).__new__(cls, value)
inst.length = length
return inst
def __setitem__(self, index, bit):
mask = 1 << self.length - index - 1
if bit == 1:
# XXX only changing local 'self'
self |= mask
elif bit == 0:
self &= ~mask
def __getitem__(self, i):
return (self >> (self.length - i -1)) & 1
def __repr__(self):
s = ''
for i in xrange(self.length):
s = str(self >> i & 1) + s
return s + " : " + str(self)
as if it were a list of bits.
Assigning bits to particular indices involves changing the value of
the integer itself, but changing 'self' obviously just alters the
value of that local variable.
Is there some way for me to change the value of the BitSequence
object itself? I've also tried wrapping and delegating using
__getattr__, but I couldn't figure out how to handle in-place methods.
Thanks for your help,
David Coffin
class BitSequence(int):
"""An integer emulating a sequence of bits, subclassing int."""
def __new__(cls, value, length=32):
inst = super(BitSequence,cls).__new__(cls, value)
inst.length = length
return inst
def __setitem__(self, index, bit):
mask = 1 << self.length - index - 1
if bit == 1:
# XXX only changing local 'self'
self |= mask
elif bit == 0:
self &= ~mask
def __getitem__(self, i):
return (self >> (self.length - i -1)) & 1
def __repr__(self):
s = ''
for i in xrange(self.length):
s = str(self >> i & 1) + s
return s + " : " + str(self)