首頁 > 軟體

一文帶你瞭解Python列舉類enum的使用

2022-10-28 14:03:03

簡介

列舉是與多個唯一常數繫結的一組符號

因為列舉表示的是常數,建議列舉元名用大寫

IntEnum 便於進行系統互動

初試

from enum import Enum


class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3


print(Color.RED)  # Color.RED
print(repr(Color.RED))  # <Color.RED: 1>
print(type(Color.RED))  # <enum 'Color'>
print(isinstance(Color.GREEN, Color))  # True
print(Color.RED.name)  # RED

遍歷

from enum import Enum


class Shake(Enum):
    VANILLA = 7
    CHOCOLATE = 4
    COOKIES = 9
    MINT = 3


for shake in Shake:
    print(shake)
# Shake.VANILLA
# Shake.CHOCOLATE
# Shake.COOKIES
# Shake.MINT

__members__ 列出 name 和成員

from enum import Enum


class Shape(Enum):
    SQUARE = 2
    DIAMOND = 1
    CIRCLE = 3
    ALIAS_FOR_SQUARE = 2


for name, member in Shape.__members__.items():
    print(name, member)
# SQUARE Shape.SQUARE
# DIAMOND Shape.DIAMOND
# CIRCLE Shape.CIRCLE
# ALIAS_FOR_SQUARE Shape.SQUARE

可雜湊

列舉元可雜湊,可用於字典和集合

from enum import Enum


class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3


apples = {}
apples[Color.RED] = 'red delicious'
apples[Color.GREEN] = 'granny smith'
print(apples)
# {<Color.RED: 1>: 'red delicious', <Color.GREEN: 2>: 'granny smith'}

存取成員

  • name:變數名
  • value:值
from enum import Enum


class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3


# 通過值存取
print(Color(1))  # Color.RED
print(Color(3))  # Color.BLUE

# 通過name存取
print(Color['RED'])  # Color.RED
print(Color['GREEN'])  # Color.GREEN

# 存取成員的name或value
print(Color.RED.name)  # RED
print(Color.RED.value)  # 1

唯一列舉值

裝飾器 @unique

from enum import Enum, unique


@unique
class Mistake(Enum):
    ONE = 1
    TWO = 2
    THREE = 3
    FOUR = 3
# ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE

自動列舉值

如果列舉值不重要,可以用 auto(), 預設從 1 開始

from enum import Enum, auto


class Color(Enum):
    RED = auto()
    BLUE = auto()
    GREEN = auto()


print(Color(1))  # Color.RED
print(list(Color))  # [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

比較運算

  • Enum 不支援直接排序
  • IntEnum 可直接排序

Enum

from enum import Enum


class Color(Enum):
    RED = 1
    BLUE = 2
    GREEN = 3


print(Color.RED is Color.RED)  # True
print(Color.RED is Color.BLUE)  # False
print(Color.RED is not Color.BLUE)  # True

try:
    Color.RED < Color.BLUE  # Enum不支援直接排序
except Exception as e:
    print(e)  # '<' not supported between instances of 'Color' and 'Color'

print(Color.BLUE == Color.RED)  # Fasle
print(Color.BLUE != Color.RED)  # True
print(Color.BLUE == Color.BLUE)  # True

print(Color.BLUE == 2)  # False

IntEnum

from enum import IntEnum


class Color(IntEnum):
    RED = 1
    BLUE = 2
    GREEN = 3


# IntEnum可直接排序
print(Color.RED < Color.BLUE)  # True

print(Color.BLUE == 2)  # True

功能性API

官方教學

from enum import Enum


class Animal(Enum):
    ANT = 1
    BEE = 2
    CAT = 3
    DOG = 4


Animal = Enum('Animal', 'ANT BEE CAT DOG')  # 同上

print(Animal)  # <enum 'Animal'>
print(Animal.ANT)  # <Animal.ANT: 1>
print(Animal.ANT.value)  # 1
print(list(Animal))  # [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]

IntEnum

官方教學

除了不可以直接和 Enum 比較,其他都類似整數

from enum import Enum, IntEnum


class Color(Enum):
    RED = 1
    GREEN = 2


class Shape(IntEnum):
    CIRCLE = 1
    SQUARE = 2


class Request(IntEnum):
    POST = 1
    GET = 2


print(Shape.CIRCLE == Color.RED)  # False

print(Shape == 1)  # False
print(Shape.CIRCLE == 1)  # True
print(Shape.CIRCLE == Request.POST)  # True

print(int(Shape.CIRCLE))  # 1
print(['a', 'b', 'c'][Shape.CIRCLE])  # b
print([i for i in range(Shape.SQUARE)])  # [0, 1]

IntFlag

官方教學

類似 int,IntFlag 成員使用按位元運運算元得到的結果仍然是 IntFlag 成員

IntFlag 和 Enum 的一個區別在於,如果沒有設定任何標誌(值為 0),則其布林值為 False

from enum import IntFlag


class Perm(IntFlag):
    R = 4  # 讀
    W = 2  # 寫
    X = 1  # 執行


print(Perm.R | Perm.W)  # <Perm.R|W: 6>
print(Perm.R + Perm.W)  # 6

RW = Perm.R | Perm.W
print(Perm.R in RW)  # True
from enum import IntFlag


class Perm(IntFlag):
    R = 4  # 讀
    W = 2  # 寫
    X = 1  # 執行
    RWX = 7  # 讀寫執行


print(Perm.RWX)  # <Perm.RWX: 7>
print(~Perm.RWX)  # <Perm.-8: -8>

print(Perm.R & Perm.X)  # <Perm.0: 0>
print(bool(Perm.R & Perm.X))  # False

print(Perm.X | 8)  # <Perm.8|X: 9>

Flag

官方教學

  • Flag 與 IntFlag 類似,成員可使用按位元運運算元進行組合,但不可與其他 Flag 或 int 組合
  • 推薦用 auto() 作為值
from enum import Flag, auto


class Color(Flag):
    BLACK = 0
    RED = auto()
    BLUE = auto()
    GREEN = auto()
    WHITE = RED | BLUE | GREEN


print(Color.RED & Color.GREEN)  # <Color.0: 0>
print(bool(Color.RED & Color.GREEN))  # False
print(Color.WHITE)  # <Color.WHITE: 7>

print(Color.BLACK)  # <Color.BLACK: 0>
print(bool(Color.BLACK))  # False

知識點

不支援同名

以上就是一文帶你瞭解Python列舉類enum的使用的詳細內容,更多關於Python列舉類enum的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com