Python枚舉類

來源:互聯網
上載者:User

標籤:ror   member   recent   last   類型   介紹   mos   ==   自訂類   

本篇主要介紹Python中枚舉類的用法,更多內容請參考:Python學習指南

當我們需要定義常量時,一個辦法就是用大寫變數通過整數來定義,例如月份:

JAN = 1FEB = 2MAR = 3···NOV = 11DEC = 12

好處就是簡單,確定是類型是int,並且仍然是變數。

更好的辦法是為這樣的枚舉類型定義一個class類型,然後,每個常量都是class的一個唯一執行個體。Python提供了Enum來來實現這個功能:

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

這樣我們就獲得了Month類型的枚舉值,可以直接使用Month.Jan來引用一個常量,或者枚舉它的所有成員:

for name, member in Month.__members__.items():    print(name, '=>', member, ',', member.value)

value屬性則是自動賦給成員int常量,預設從1開始計數。

如果需要更精確地控制枚舉類型,可以從Enum派生出自訂類:

@uniqueclass Weekday(Enum):    Sun = 0    Mon = 1    Tue = 2    Wed = 3    Thu = 4    Fri = 5    Sat = 6

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

訪問這些枚舉類型可以有若干種方法:

>>> day1 = Weekday.Mon>>> print(day1)Weekday.Mon>>> print(Weekday.Tue)Weekday.Tue>>> print(Weekday['Tue'].name)Tue>>> print(Weekday.Tue.value)2>>> print(day1 == Weekday.Mon)True>>> print(day1 == Weekday.Tue)False>>> print(Weekday(1))Weekday.Mon>>> print(day1 == Weekday(1))True>>> Weekday(7)Traceback (most recent call last):  ...ValueError: 7 is not a valid Weekday>>> for name, member in Weekday.__members__.items():...     print(name, '=>', member)...Sun => Weekday.SunMon => Weekday.MonTue => Weekday.TueWed => Weekday.WedThu => Weekday.ThuFri => Weekday.FriSat => Weekday.Sat

Python枚舉類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.