11 class EnumClass(object):
13 def __iter__(self):
return iter(constants)
14 def __len__(self):
return len(constants)
15 def __getitem__(self, i):
return constants[i]
16 def __repr__(self):
return 'Enum' + str(names)
17 def __str__(self):
return 'enum ' + str(constants)
19 class EnumValue(object):
20 __slots__ = (
'__value')
21 def __init__(self, value): self.__value = value
22 Value = property(
lambda self: self.__value)
23 EnumType = property(
lambda self: EnumType)
24 def __hash__(self):
return hash(self.__value)
25 def __cmp__(self, other):
28 assert self.EnumType
is other.EnumType,
"Only values from the same enum are comparable"
29 return cmp(self.__value, other.__value)
30 def __invert__(self):
return constants[maximum - self.__value]
31 def __nonzero__(self):
return bool(self.__value)
32 def __repr__(self):
return str(names[self.__value])
34 maximum = len(names) - 1
35 constants = [
None] * len(names)
36 for i, each
in enumerate(names):
38 setattr(EnumClass, each, val)
40 constants = tuple(constants)
41 EnumType = EnumClass()
45 if __name__ ==
'__main__':
46 print '\n*** Enum Demo ***'
47 print '--- Days of week ---'
48 Days =
Enum(
'Mo',
'Tu',
'We',
'Th',
'Fr',
'Sa',
'Su')
52 print Days.Mo < Days.Fr
56 print '--- Yes/No ---'
57 Confirmation =
Enum(
'No',
'Yes')
58 answer = Confirmation.No
59 print 'Your answer is not', ~answer