python 枚舉enum

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.......python

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
相關文章
相關標籤/搜索