python列舉型別 python基礎 列舉類

2021-10-11 15:01:35 字數 2224 閱讀 4614

#python 列舉類 示例#2016-8-30 18:55:25#mengmengcoding#-*- coding: utf-8 -*-

from enum importenum#enum是乙個列舉類#month,weekday各為乙個enum類的例項化

month=enum('month',('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'))

weekday=enum('weekday',('mon','tue','wed','thu','fri','sat','sun'))for name,member in month.__members__.items():print(name,'=>',member,',',member.value)print('--------cut-off line--------')#輸出:

'''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'''

for name,member in weekday.__members__.items():print(name,'=>',member,',',member.value)print('--------cut-off line--------')#輸出:

'''mon => weekday.mon , 1

tue => weekday.tue , 2

wed => weekday.wed , 3

thu => weekday.thu , 4

fri => weekday.fri , 5

sat => weekday.sat , 6

sun => weekday.sun , 7'''

#如果需要更精確地控制列舉型別,可以從enum派生出自定義類#這裡還是用周來舉例吧,誰讓我見識少呢~#用weekday來區別之前的weekday吧

from enum importenum,unique

@unique#@unique裝飾器可以幫助我們檢查保證沒有重複值

class weekday(enum): #由enum類派生得到

sun=0

mon=1tue=2wed=3thu=4fri=5sat=6day1=weekday.monprint('day1=',day1)print('weekday.tue=',weekday.tue)print('weekday[\'tue\']=',weekday['tue'])print('weekday.tue.value=',weekday.tue.value)print('day1==weekday.mon ?',day1==weekday.mon)print('day1==weekday.tue ?',day1==weekday.tue)print('day1==weekday(1) ?',day1==weekday(1))#輸出:

'''day1= weekday.mon

weekday.tue= weekday.tue

weekday['tue']= weekday.tue

weekday.tue.value= 2

day1==weekday.mon ? true

day1==weekday.tue ? false

day1==weekday(1) ? true'''

print('--------cut-off line--------')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'''

Python 列舉型別

列舉型別可以看作是一種標籤或是一系列常量的集合,通常用於表示某些特定的有限集合,例如星期 月份 狀態等。在沒有專門提供列舉型別的時候我們是怎麼做呢,一般就通過字典或類來實現 color class color red 1 green 2 blue 3這種來實現列舉如果小心翼翼地使用當然沒什麼問題,畢...

Python 的列舉型別

python 的原生型別中並不包含列舉型別。為了提供更好的解決方案,python 通過 pep 435 在 3.4 版本中新增了enum標準庫。列舉型別可以看作是一種標籤或是一系列常量的集合,通常用於表示某些特定的有限集合,例如星期 月份 狀態等。在沒有專門提供列舉型別的時候我們是怎麼做呢,一般就通...

Python 的列舉型別

python 的原生型別中並不包含列舉型別。為了提供更好的解決方案,python 通過 pep 435 在 3.4 版本中新增了enum標準庫。列舉型別可以看作是一種標籤或是一系列常量的集合,通常用於表示某些特定的有限集合,例如星期 月份 狀態等。在沒有專門提供列舉型別的時候我們是怎麼做呢,一般就通...