Equivalent to C bitmasks and enumerations

Dave Angel davea at ieee.org
Thu Apr 16 08:10:22 EDT 2009


John Machin wrote:
> On Apr 16, 10:13 am, Dave Angel <da... at ieee.org> wrote:
>   
>> For the Color example, how's this for a starting place:
>>
>> class Color(object):
>>     def __init__(self, name, enum):
>>         self.enum =num
>>         self.name =ame
>>         setattr(Color, name, self)
>>
>>     @staticmethod
>>     def seal():
>>         del Color.__init__
>>         del Color.seal
>>
>>     def __str__(self):
>>         return self.name
>>
>> Color("RED", 4)
>> Color("GREEN", 11)
>> Color.seal()        #prevent any new instances from being created
>>
>> b =olor.RED
>> print type(b)
>> print str(b)
>>
>> a =olor.GREEN
>> print a
>>     
>
> So when you use Color.GREEN in an expression or pass it as a function/
> method argument, it produces "GREEN" ... doesn't emulation of a C-
> style enum require it to produce 11?
>
>   
>> print a.enum
>>     
>
>   
C-style enums have their limitations.  In any case, the OP had specific 
requirements, and I came close to meeting them.  I figured the purpose 
was to accomplish the same goal (or better) as enums do in C.  So the 
object should be able to be passed around without regard to its 
"value."  And it's printable value is "GREEN".  But if it's used as a 
lookup in a dictionary, it just works right, without getting confused 
with an integer that might also be in the dictionary.




More information about the Python-list mailing list