Python的学习笔记--枚举

枚举

python中,枚举使用Enum模块。 具体使用如下:

1
2
3
4
5

from enum import Enum

Week=Enum("Week",('Mon','Tue','Wen','Thu','Fri','Sta','Sun'))

在枚举中可以自动为下面的变量赋值,我们可以使用迭代把数据显示出来:

1
2
3
4
5
from enum import Enum
Week=Enum("Week",('Mon','Tue','Wen','Thu','Fri','Sta','Sun'))

for k, v in Week.__members__.items():
print(k, ':', v, ',', v.value)

打印结果:

1
2
3
4
5
6
7
Mon : Week.Mon , 1
Tue : Week.Tue , 2
Wen : Week.Wen , 3
Thu : Week.Thu , 4
Fri : Week.Fri , 5
Sta : Week.Sta , 6
Sun : Week.Sun , 7

如果像自定义枚举的值,可以使用继承的方法,自定义一个枚举:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from enum import Enum, unique

class Week(Enum):
Sun = 0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6

for k, v in Week.__members__.items():
print(k, ':', v, ',', v.value)

打印结果:

1
2
3
4
5
6
7
Sun : Week.Sun , 0
Mon : Week.Mon , 1
Tue : Week.Tue , 2
Wed : Week.Wed , 3
Thu : Week.Thu , 4
Fri : Week.Fri , 5
Sat : Week.Sat , 6

可以使用@unique装饰器来保证值的唯一。

1
2
3
4
5
6
7
8
9
10
11
12
from enum import Enum, unique

@unique
class Week(Enum):
Sun = 0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
Sat = 6

上面的代码会报错:TypeError: Attempted to reuse key: 'Sat'

对于枚举的使用可以用Week.Sun取枚举的值,Week.Sun.value来取对应的整型的值。