Source From Here
Prefaceenum 是 Python 裏用來建立枚舉形態的標準函式庫。enum 算是比較新的標準函式庫,學習 enum 可以讓你輕鬆建立枚舉,改寫以前單獨使用 const variable 的狀況:
Quickstart Tutorial
從今天開始,讓我們把這樣枚舉的 Code:
- # -*- coding: utf-8 -*-
- # Input Type
- TRACK = 'track'
- ALBUM = 'album'
- ARTIST = 'atrist'
- PLAYLIST = 'playlist'
- # Response Type
- OK = 'ok'
- NO_RESULT = 'no_result'
- # -*- coding: utf-8 -*-
- from enum import Enum
- class InputType(Enum):
- TRACK = 'track'
- ALBUM = 'album'
- ARTIST = 'atrist'
- PLAYLIST = 'playlist'
- class ResponseType(Enum):
- OK = 'ok'
- NO_RESULT = 'no_result'
透過 enum member 可以取得 name 或是 value:
透過 enum class 可以取得 enum member:
不同的 enum class 雖然有相同的 enum value,但比較結果是不相同的:
- >>> import enum
- >>> class Shape(enum.Enum)
- ... SQUARE = 1
- ... CIRCLE = 2
- ...
- >>> class Response(enum.Enum):
- ... OK = 1
- ... BAD = 2
- ...
- >>> Shape.SQUARE == Response.OK
- False
其實應該要透過 globals() + IntEnum 才能直接將 enum member 當 int 用:
- >>> class Animal(IntEnum):
- ... DOG = 1
- ... CAT = 2
- ... PANDA = 3
- ...
- >>> globals().update(Animal.__members__)
- >>> DOG
- <Animal.DOG: 1>
- >>> DOG == 1
- True
- >>>
使用 IntEnum 來簡化整數枚舉比對
透過 IntEnum 我們可以讓整數枚舉的比對變得更輕鬆一點:
- >>> import enum
- >>> class Shape(enum.IntEnum):
- ... SQUARE = 1
- ... CIRCLE = 2
- ... TRIANGLE = 3
- ...
- >>> Shape.SQUARE == 1
- True
- >>> Shape.CIRCLE == 2
- True
- >>> Shape.TRIANGLE == 1
- False
- >>> import enum
- >>> class Mac(enum.IntEnum):
- ... AIR = 6
- ... PRO = 7
- ...
- >>> class Android(enum.IntEnum):
- ... MARSHMALLOW = 6
- ... NOUGAT = 7
- ...
- >>> Mac.AIR == Android.MARSHMALLOW
- True
我們可以透過繼承來達到前面 IntEnum 的效果,例如說要製作 StrEnum:
- >>> import enum
- >>> class StrEnum(str, enum.Enum):
- ... pass
- ...
- >>> class Browser(StrEnum):
- ... FIREFOX = 'firefox'
- ... CHROME = 'chrome'
- ...
- >>> Browser.FIREFOX == 'firefox'
- True
- >>> Browser.CHROME == 'chromium'
- False
如果是 IntFlag,執行 bitwise 操作 (&, |, ^, ~),回傳結果還會是 IntFlag 成員。如果是其他操作則會回傳 int:
- >>> class Permission(enum.IntFlag):
- ... R = 4
- ... W = 2
- ... X = 1
- ...
- >>> Permission.R | Permission.W
- <Permission.R|W: 6>
- >>> Permission.R | Permission.X
- <Permission.R|X: 5>
- >>> Permission.R + Permission.X
- 5
- >>> RW = Permission.R | Permission.W
- >>> Permission.R in RW
- True
- >>> import enum
- >>> Animal = enum.Enum('Animal', 'CAT DOG PANDA')
- >>> Animal
- <enum 'Animal'>
- >>> Animal.CAT
- <Animal.CAT: 1>
- >>> Animal.DOG
- <Animal.DOG: 2>
- >>> Animal.PANDA
- <Animal.PANDA: 3>
- >>>
沒有留言:
張貼留言