Enumeration Programming
Why, When
This Implementation is really near to the UML description of <<Enumeration>>. It uses new style class.
Code
Toggle line numbers
1 # code is public domain
2 import sets
3
4 class Enumeration(object):
5
6 def __new__(cls, arg):
7 if hasattr(cls, arg):
8 return getattr(cls,arg)
9 else:
10 return object.__new__(cls, arg)
11
12 def __init__(self, name):
13 self._name = name
14 setattr(self.__class__, name, self)
15
16 def __str__(self):
17 return '#%s' % str(self._name)
18
19 def __repr__(self):
20 return "%s('%s')" % (self.__class__.__name__, self._name)
21
22 def getEnumerationSet(cls):
23 result = sets.Set()
24 for attr in dir(cls):
25 attr = getattr(cls, attr)
26 if isinstance(attr, Enumeration):
27 result.add(attr)
28 return result
29 getEnumerationSet = classmethod(getEnumerationSet)
Example
Toggle line numbers
1 class PrimaryColorKind(Enumeration):
2 pass
3 PrimaryColorKind('Rouge')
4 PrimaryColorKind('Vert')
5 PrimaryColorKind('Bleu')
6
7 print str(PrimaryColorKind.Rouge), str(PrimaryColorKind.Vert), str(PrimaryColorKind.Bleu)
8 print PrimaryColorKind.getEnumerationSet()
9
10 class ColorKind(PrimaryColorKind):
11 pass
12 ColorKind('Violet')
13
14
15 print str(ColorKind.Rouge), str(ColorKind.Violet)
16 print ColorKind.getEnumerationSet()
17 print repr(ColorKind.Rouge), repr(ColorKind.Violet)
18 assert(ColorKind.Rouge is ColorKind('Rouge'))
output is :
#Rouge #Vert #Bleu Set([PrimaryColorKind('Vert'), PrimaryColorKind('Rouge'), PrimaryColorKind('Bleu')]) #Rouge #Violet Set([PrimaryColorKind('Vert'), PrimaryColorKind('Rouge'), ColorKind('Violet'), PrimaryColorKind('Bleu')]) PrimaryColorKind('Rouge') ColorKind('Violet') mirville Python 79 % python Enumeration.py #Rouge #Vert #Bleu Set([PrimaryColorKind('Vert'), PrimaryColorKind('Rouge'), PrimaryColorKind('Bleu')]) #Rouge #Violet Set([PrimaryColorKind('Vert'), PrimaryColorKind('Rouge'), ColorKind('Violet'), PrimaryColorKind('Bleu')]) PrimaryColorKind('Rouge') ColorKind('Violet')