[Tutor] What is __weakref__ ?

Karim karim.liateni at free.fr
Tue Jan 18 15:34:12 CET 2011


Hello Bob,

Thanks for this better and simple approach!
To be perfect I would like to be able to do.
 >>> type = CategoryType()
 >>> type.TRANSISTOR
0
I will use your enums declaration and the range part to use as keys for 
enums.
And I will raise a KeyError in toString() to handle invalid litteral.

Thanks!

Regards
Karim


On 01/18/2011 02:24 PM, bob gailer wrote:
> On 1/18/2011 8:08 AM, Karim wrote:
>>
>> I know this is ugly but until now it is the only way (with this side 
>> effect) I found to declare Enums class that I _understand_:
>>
>> *class CategoryType(object):
>>     """Implements the enumeration and prevent associated newly created
>>     instances to redefine enums value via special class variable 
>> '__slots__'
>>     definition. It makes also, instances have no attributes at all.
>>     """
>>     __slots__ = ()
>>
>>     TRANSISTOR, MOS, BIPOLAR, CAPACITOR, RESISTOR, DIODE, ESD, PAD, \
>>     COMPARATOR, OPAMP, ADC, DAC, PLL, OTHER = range(14)
>>
>>     def toString ( self, litteral ):
>>         """Convert the litteral integer number to its associated 
>> string representation."""
>>         if litteral == self.TRANSISTOR:
>>           return 'transistor'
>>         elif litteral == self.MOS:
>>           return 'mos'
>>         elif litteral == self.BIPOLAR:*
>> [...]
> IMHO this just cries out for a dictionary:
>
> class CategoryType(object):
>   __slots__ = ()
>   enums = {
>     0: 'transistor',
>     1: 'mos',
>     ...
>     }
>   def toString(self, literal):
>     """Convert the literal integer number to its associated string 
> representation."""
>     return self.enums[literal]
>
> Note this does not handle invalid literal.
>
> If you are happy with range 14) you could alternatively use a list:
>   enums = ['transistor, 'mos',  ...]
>
> -- 
> Bob Gailer
> 919-636-4239
> Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110118/084b3841/attachment.html>


More information about the Tutor mailing list