1. 程式人生 > >python 學習彙總56:Enum類(初級學習- tcy)

python 學習彙總56:Enum類(初級學習- tcy)

Enum類  2018/8/12 
1.應用:
定義常量時value屬性則是自動賦給成員的int常量,預設從1開始計數

from enum import Enum

Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))

type(Month),type(Month.Jan)#(enum.EnumMeta, <enum 'Month'>) 

屬性:
Month.Feb.name#'Feb'
Month.Feb.value#2 

 

for name, member in Month.__members__.items():
print(name, '=>', member, ',', member.value)#輸出見備註1

for i in Month:
print(i,i.name,i.value) #輸出見備註1 

  

2.精確地控制列舉型別從Enum派生出自定義類:

from enum import Enum, unique

@unique #檢查保證沒有重複值
class Weekday(Enum):
Sun = 0 # Sun的value被設定為0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6 

 

屬性:
day1.name# 'Mon'
day1.value#1
day1.Sun.name# 'Sun'
day1.Sun.value#0

訪問列舉型別:
day1 = Weekday.Mon #<Weekday.Mon: 1>
print(Weekday.Tue) #Weekday.Tue
print(Weekday['Tue']) #Weekday.Tue
print(Weekday.Tue.value) #2
print(Weekday(1)) #Weekday.Mon    
備註1:
輸出:

Jan => Month.Jan , 1

  Month.Jan Jan   1
Feb => Month.Feb , 2   Month.Feb Feb 2
Mar => Month.Mar , 3   Month.Mar Mar 3
Apr => Month.Apr , 4   Month.Apr Apr 4
May => Month.May , 5   Month.May May 5
Jun => Month.Jun , 6   Month.Jun Jun 6
Jul => Month.Jul , 7   Month.Jul Jul 7
Aug => Month.Aug , 8   Month.Aug Aug 8
Sep => Month.Sep , 9   Month.Sep Sep 9
Oct => Month.Oct , 10   Month.Oct Oct 10
Nov => Month.Nov , 11   Month.Nov Nov 11
Dec => Month.Dec , 12   Month.Dec Dec 12