您好,登錄后才能下訂單哦!
注:python 3.x版本才能使用
枚舉格式:
from enum import Enum
新類名 = Enum(變量統稱名,(變量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)))
運行結果:
[(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)
運行結果:
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. 當Class中有重復值時,會返回第一個,其他忽略
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)
運行結果:
Weekday.monday Weekday.wensdday Weekday.thursday Weekday.friday
手動打Enum值時,一不小心打錯了怎么辦,又得一個個找,真麻煩。所以,有人想,如果有個方法能夠檢查重復值就好了,于是:@unique就出來了
from enum import Enum, @unique class Weekday(Enum): monday = 1 tusday = 1 wensdday =3 thursday =9 friday =5 print (Weekday(1))
運行結果:
Traceback (most recent call last): File "/usercode/file.py", line 7, in <module> class Weekday(Enum): File "/usr/lib/python3.4/enum.py", line 524, in unique (enumeration, alias_details)) ValueError: duplicate values found in <enum 'Weekday'>: tusday -> monday
4.有人也在想,我就是不改咋地!我能不能通過另一個方法把成員都打印出來?于是:__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)
運行結果:
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 )
運行結果:
False False Traceback (most recent call last): File "/usercode/file.py", line 16, in <module> print (Weekday.tusday > Weekday.friday ) TypeError: unorderable types: Weekday() > Weekday()
看到一個很好很好的Blog,這講的內容,他的比廖某的還要簡潔明了。很喜歡。我的怎么亂?我純粹是做筆記,沒想那么多,要改構造想多了反而浪費時間。
https://blog.csdn.net/xionghuixionghui/article/details/66476601
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。