Python Enum 枚举 用法汇总
1 import os
2 import sys
3 if sys.version_info.major + sys.version_info.minor * 0.1 < 3.4:
4 from enum34 import Enum
5 else:
6 from enum import Enum
7
8 class MyColorEnum(Enum):
9 red = 1
10 red_alias = 1
11 blue = 2
12 green = 'green'
13
14 MyColorEnum.red.name # get member name string
15 MyColorEnum.red.value # get member value
16
17 for c in MyColorEnum:
18 print(c) # just one of MyColorEnum.red_alias and MyColorEnum.red, according to the order which itself decides
19
20 for c in MyColorEnum.__members__.items():
21 c[0] # str name eg. 'red'
22 c[1] # member eg. MyColorEnum.red
23 # contain 'red_alias' and MyColorEnum.red_alias
24
25 'red' in MyColorEnum.__members__ # if member name in Enum
26 0 in MyColorEnum._value2member_map_ # if value in Enum values
27
28 MyColorEnum.__members__['red'] # MyColorEnum.red, get member by member name string, if no such member name string, raising KeyError
29
30 # comparation ################################################################################
31 MyColorEnum.red is MyColorEnum.red_alias # True
32 MyColorEnum.red == MyColorEnum.red_alias # True
33 MyColorEnum.red != MyColorEnum.red_alias # False
34 #never do this
35 #MyColorEnum.red < MyColorEnum.blue # raising TypeError, Enum values could be different types