This article mainly introduces five methods to simulate the enum enumeration type in Python. This article provides the implementation code directly, you can refer to the following methods to simulate enum: (I think the method is simple and practical)
The 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']