【Python】Python枚举Enum

介绍

在 Python 中,Enum(枚举)是一种用于定义一组命名常量的类。它可以提高代码的可读性,防止使用魔法数字(magic numbers),并确保变量的值只能是预定义的选项之一。

定义 Enum

Python 提供了 enum 模块,可以用 Enum 类来定义枚举:

1
2
3
4
5
6
from enum import Enum

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

访问枚举成员

1
2
3
print(Color.RED)         # Color.RED
print(Color.RED.name)    # RED
print(Color.RED.value)   # 1

遍历枚举

可以使用 for 循环遍历枚举:

1
2
3
4
5
6
for color in Color:
    print(color.name, color.value)

# RED 1
# GREEN 2
# BLUE 3

成员比较

可以使用 is 或 == 进行比较:

1
2
3
4
5
if Color.RED is Color.RED:
    print("Same member")

if Color.RED == Color(1):
    print("Same value")

枚举的唯一性

默认情况下,枚举成员的值可以重复,但可以使用 @unique 装饰器强制唯一:

1
2
3
4
5
6
7
8
from enum import Enum, unique

@unique
class UniqueColor(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
    # YELLOW = 1  # 这行会报错 / This line will cause an error

自动赋值枚举

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from enum import Enum, auto

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

print(AutoColor.RED.value)   # 1
print(AutoColor.GREEN.value) # 2
print(AutoColor.BLUE.value)  # 3

IntEnum(整数枚举)

如果想让枚举成员表现得像整数,可以使用 IntEnum:

1
2
3
4
5
6
7
8
9
from enum import IntEnum

class Status(IntEnum):
    SUCCESS = 200
    NOT_FOUND = 404
    ERROR = 500

print(Status.SUCCESS == 200)  # True
print(Status.SUCCESS + 100)   # 300

注意:普通 Enum 不能直接与整数进行数学运算,而 IntEnum 可以。

成员别名

如果多个成员的值相同,只有第一个定义的成员会作为正式成员,其他的是别名:

1
2
3
4
5
6
7
8
class Shape(Enum):
    CIRCLE = 1
    OVAL = 2
    ELLIPSE = 2  # 这是 OVAL 的别名 / This is an alias for OVAL

print(Shape.OVAL)        # Shape.OVAL
print(Shape.ELLIPSE)     # Shape.OVAL
print(Shape.OVAL is Shape.ELLIPSE)  # True

自定义方法

1
2
3
4
5
6
7
8
class Message(Enum):
    HELLO = "Hello"
    GOODBYE = "Goodbye"

    def describe(self):
        return f"Message: {self.value}"

print(Message.HELLO.describe())  # Message: Hello
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计