Share the following five methods for simulating enum enumeration in Python: pythonenum
The following methods are used to simulate enum: (sensory method 1 is simple and practical)
Copy codeThe Code is as follows:
# Way1
Class Directions ctions:
Up = 0
Down = 1
Left = 2
Right = 3
Print Directions. down
# Way2
DirUp, dirDown, dirLeft, dirRight = range (4)
Print dirDown
# Way3
Import collections
Dircoll = collecoll. namedtuple ('direction', ('up', 'drop', 'left', 'right '))
Directions = dircoll (0, 1, 2, 3)
Print directions. DOWN
# Way4
Def enum (args, start = 0 ):
Class Enum (object ):
_ Slots _ = args. split ()
Def _ init _ (self ):
For I, key in enumerate (Enum. _ slots __, start ):
Setattr (self, key, I)
Return Enum ()
E_dir = enum ('up down left right ')
Print e_dir.down
# Way5
# Some times we need use enum value as string
Ctions = {'up': 'up', 'down': 'low', 'left': 'left', 'right': 'right '}
Print Directions ['low']