enum枚举是常用的功能
from enum import Enum
shapes = Enum('shape', ('Line', 'Points', 'Polyline', 'Polygon', 'Rectangle', 'Rounded Rectangle', 'Ellipse',
'Arc', 'Chord', 'Pie', 'Path', 'Text', 'Pixmap'))
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
print(shapes._member_map_) #__dict__
#OrderedDict([('Line', <shape.Line: 1>), ('Points', <shape.Points: 2>), ('Polyline', <shape.Polyline: 3>), ('Polygon', <shape.Polygon: 4>), ('Rectangle', <shape.Rectangle: 5>), ('Rounded Rectangle', <shape.Rounded Rectangle: 6>), ('Ellipse', <shape.Ellipse: 7>), ('Arc', <shape.Arc: 8>), ('Chord', <shape.Chord: 9>), ('Pie', <shape.Pie: 10>), ('Path', <shape.Path: 11>), ('Text', <shape.Text: 12>), ('Pixmap', <shape.Pixmap: 13>)])
shape = shapes['Pie']
print(shape)
print('%s: name %s ,num is %s '%(shapes['Pie'], shapes['Pie'].name, shapes['Pie'].value ))
shape = shapes(3)
print(Month._member_map_.__len__())
class WEEKDAY(Enum):
Sun = 7 # Sun的value被设定为0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
for p,d in WEEKDAY.__members__.items():
print(p)
print(p, ':', d.name, ',', d.value,'(', d, ')')
print(WEEKDAY['Sun'])
print(WEEKDAY.__len__())
1. 首先,定义枚举要导入enum模块。
2. 枚举定义继承Enum类,定义类用class关键字,。
注意:
定义枚举时,成员名称不允许重复
默认情况下,不同的成员值允许相同。但是两个相同值的成员,第二个成员的名称被视作第一个成员的别名
如果枚举中存在相同值的成员,在通过值获取枚举成员时,只能获取到第一个成员
如果要限制定义枚举时,不能定义相同值的成员。可以使用装饰器@unique【要导入unique模块】
每一个成员可以用shapes(3)或shapes[‘Pie’]来访问,分别具有属性name和value,合起来构成dict: _member_map_