枚舉類型:在實際問題中,有些變量的值被限定在一個有限的範圍內。例如:一個星期有且只有7天,一年有且只有十二個月,一個班每週有6門課程等等。若是把這些量說明爲整型、字符串或者其餘類型顯然是不合適。編程界爲此提供了一種稱爲枚舉的類型。在枚舉類型定義中列舉出全部可能的取值,被說明爲該枚舉類型的變量取值範圍不能超過定義的範圍。枚舉是一種基本的數據類型,由於它不能再分解爲任何基本類型。python
python中,通常的會爲枚舉類型定義一個class類型,而後每一個常量都是class的一個惟一的實例。Enum類實現了這個功能:編程
>>> from enum import Enum >>> Month = Enum('Month',('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')) >>> for name,member in Month.__members__.items(): ... print(name,',',member,',',member.value) ... Jan , Month.Jan , 1 Feb , Month.Feb , 2 Mar , Month.Mar , 3 Apr , Month.Apr , 4 May , Month.May , 5 Jun , Month.Jun , 6 Jul , Month.Jul , 7 Aug , Month.Aug , 8 Sep , Month.Sep , 9 Oct , Month.Oct , 10 Nov , Month.Nov , 11 Dec , Month.Dec , 12
上面咱們定義了一個Month類型的枚舉類,而後枚舉出它的全部的成員。其中,value屬性是自動賦值給成員的int型常量,默認從1開始。spa
若是須要更精確的控制枚舉類型,能夠從Enum派生出自定義類,同時利用@unique裝飾器幫助咱們檢查有沒有重複值。code
>>> from enum import Enum,unique >>> @unique ... class Weekday(Enum): ... Sun = 0 ... Mon = 1 ... Tue = 2 ... Wed = 3 ... Thu = 4 ... Fri = 5 ... Sat = 6 ... >>> day1 = Weekday.Mon >>> day1 <Weekday.Mon: 1> >>> print(day1) Weekday.Mon >>> print(Weekday.Tue) Weekday.Tue >>> print(Weekday['Tue']) Weekday.Tue >>> print(Weekday.Tue.value) 2 >>> day1 == Weekday.Mon True >>> Weekday(1) <Weekday.Mon: 1> >>> Weekday(3) <Weekday.Wed: 3> >>> for name,member in Weekday.__members__.items(): ... print(name,':',member) ... Sun : Weekday.Sun Mon : Weekday.Mon Tue : Weekday.Tue Wed : Weekday.Wed Thu : Weekday.Thu Fri : Weekday.Fri Sat : Weekday.Sat