python 枚举enum
2020-11-20 19:06 清风软件测试开发 阅读(113) 评论(0) 编辑 收藏 举报python 枚举enum
from enum import Enum class EnumTest(Enum): spring = [1,2,3] summer = [4,5,6] autumn = [7,8,9] winter = [10,11,12] print(EnumTest.spring) #输出 EnumTest.spring print(EnumTest.summer) #输出 EnumTest.summer print(EnumTest.autumn) #输出 EnumTest.autumn print(EnumTest.winter) #输出 EnumTest.winter print(type(EnumTest.spring)) #输出 <enum 'EnumTest'> print(type(EnumTest.summer)) #输出 <enum 'EnumTest'> print(type(EnumTest.autumn)) #输出 <enum 'EnumTest'> print(type(EnumTest.winter)) #输出 <enum 'EnumTest'> print(EnumTest.spring.name) #输出 spring print(EnumTest.summer.name) #输出 summer print(EnumTest.autumn.name) #输出 autumn print(EnumTest.winter.name) #输出 winter print(EnumTest.spring.value) #输出 [1,2,3] print(EnumTest.summer.value) #输出 [4,5,6] print(EnumTest.autumn.value) #输出 [7,8,9] print(EnumTest.winter.value) #输出 [10,11,12]
除了用类来创建枚举,还可以直接用Enum()创建枚举,默认的序号/value是1,2,3,4,5.......
YearSeason = Enum('season',('spring','summer','autumn','winter')) for name,member in YearSeason.__members__.items(): print(name,'==>',member.value,'==>',member) #输出:spring ==> 1 ==> season.spring #输出:summer ==> 2 ==> season.summer #输出:autumn ==> 3 ==> season.autumn #输出:winter ==> 4 ==> season.winter print(YearSeason) #输出:<enum 'season'> print(YearSeason(1)) #输出:season.spring print(YearSeason(2)) #输出:season.summer print(YearSeason(3)) #输出:season.autumn print(YearSeason(4)) #输出:season.winter print('========================================================') print(len(YearSeason)) #输出:4 print('========================================================') print(YearSeason.spring) #输出:season.spring print(YearSeason['spring']) #输出:season.spring print('========================================================')
for i in range(1,(len(YearSeason)+1)): print(YearSeason(i)) #输出:season.spring #输出:season.summer #输出:season.autumn #输出:season.winter
Enum