Can I reference 1 instance of an object by more names ? rephrase
Bruno Desthuilliers
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu May 24 04:02:35 EDT 2007
Maric Michaud a écrit :
> Stef Mientki a écrit :
(snip)
>> # 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()
As a side note, properties are just an example of objects using the
descriptor protocol. You can build your own descriptors for more
advanced use (think : 'smart' attributes):
http://users.rcn.com/python/download/Descriptor.htm
http://docs.python.org/ref/descriptors.html
More information about the Python-list
mailing list