Stef Mientki a écrit : > hi Bruno, > > after study it carefully, > it's much more complex than I thought > (I can't understand it completely, which is of less importance). > Your solution works great, > but I need one little extension, > which I can create, but just at the cost of a lot of code. > Maybe you can give me another hint. > >> In the first case, this is *really* a binding, and that's one of the few >> things that Python won't let you mess with. In the two last cases, it's >> in fact a method call - as the use of __[get|set]item__ should make >> obvious. >> >> here's an example using a property: >> >> class cpu_ports(object): >> def __init__(self, value=0): >> self._d = value >> @apply >> def value(): >> def fset(self, value): >> print 'vv' >> self._d = value >> def fget(self): >> return self._d >> return property(**locals()) > > # I need to read and write the individual bits of the byte object > # so I can create 8 blocks of code like this, one for each bit position > # I use it, like this > # name1 = cpu_ports() > # name1.p5 = True > # or > # name1.p[5] = True > > @apply # read / write bit 5 > def p5(): > def fset(self, value): > index = 5 > value = ( value & 1L ) << index > mask = ( 1L ) << index > self._d = ( self._d & ~mask ) | value > def fget(self): > index = 5 > return ( self._d >> index ) & 1 > return property(**locals()) > > I can optimize the above code a little bit, > but I've the feeling that I don't need to repeat this code 8 times.
something like that should just work (untested) : def bit(): def fset(self, value): index = 5 value = ( value & 1L ) << index mask = ( 1L ) << index self._d = ( self._d & ~mask ) | value def fget(self): index = 5 return ( self._d >> index ) & 1 return property(**locals()) class cpu_ports(object) : p1 = bit() p2 = bit() p3 = bit() p4 = bit() p5 = bit() But i wonder if you shouldn't use arrays instead : In [6]:import array In [7]:help(array) -- http://mail.python.org/mailman/listinfo/python-list