注:python 3.x版本才能使用
專注于為中小企業(yè)提供網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)上蔡免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動(dòng)了近1000家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
枚舉格式:
from enum import Enum
新類名 = Enum(變量統(tǒng)稱名,(變量1,變量2....))
Month = Enum('month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
1.
seasons = ['Spring', 'Summer', 'Fall', 'Winter'] print (list(enumerate(seasons)))
運(yùn)行結(jié)果:
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
2.
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)
運(yùn)行結(jié)果:
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
3. 當(dāng)Class中有重復(fù)值時(shí),會(huì)返回第一個(gè),其他忽略
from enum import Enum class Weekday(Enum): monday = 1 tusday = 1 wensdday =3 thursday =9 friday =5 #print (Weekday(1)) for n in Weekday: print (n)
運(yùn)行結(jié)果:
Weekday.monday Weekday.wensdday Weekday.thursday Weekday.friday
手動(dòng)打Enum值時(shí),一不小心打錯(cuò)了怎么辦,又得一個(gè)個(gè)找,真麻煩。所以,有人想,如果有個(gè)方法能夠檢查重復(fù)值就好了,于是:@unique就出來了
from enum import Enum, @unique class Weekday(Enum): monday = 1 tusday = 1 wensdday =3 thursday =9 friday =5 print (Weekday(1))
運(yùn)行結(jié)果:
Traceback (most recent call last): File "/usercode/file.py", line 7, inclass Weekday(Enum): File "/usr/lib/python3.4/enum.py", line 524, in unique (enumeration, alias_details)) ValueError: duplicate values found in : tusday -> monday
4.有人也在想,我就是不改咋地!我能不能通過另一個(gè)方法把成員都打印出來?于是:__members__就出來了
from enum import Enum class Weekday(Enum): monday = 1 tusday = 1 wensdday = 3 thursday = 9 friday = 5 for n,y in Weekday.__members__.items(): print (n, '--', y, '--', y.value) f = Weekday.thursday print (f.value)
運(yùn)行結(jié)果:
monday -- Weekday.monday -- 1 tusday -- Weekday.tusday -- 1 wensdday -- Weekday.wensdday -- 3 thursday -- Weekday.thursday -- 9 friday -- Weekday.friday -- 5 9
5.枚舉比較:不能比大小??!能比同值
from enum import Enum, unique #@unique class Weekday(Enum): monday = 1 tusday = 1 wensdday =3 thursday =9 friday =5 print (Weekday.monday == Weekday.wensdday) print (Weekday.tusday is Weekday.friday ) print (Weekday.tusday > Weekday.friday )
運(yùn)行結(jié)果:
False False Traceback (most recent call last): File "/usercode/file.py", line 16, inprint (Weekday.tusday > Weekday.friday ) TypeError: unorderable types: Weekday() > Weekday()
看到一個(gè)很好很好的Blog,這講的內(nèi)容,他的比廖某的還要簡潔明了。很喜歡。我的怎么亂?我純粹是做筆記,沒想那么多,要改構(gòu)造想多了反而浪費(fèi)時(shí)間。
https://blog.csdn.net/xionghuixionghui/article/details/66476601