Python Enum

Posted by Adam on August 24, 2022
from enum import Enum

# 定義一個枚舉類型
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

# 使用枚舉值
print(Color.RED)        # 輸出: Color.RED
print(Color(2))         # 輸出: Color.GREEN
print(Color.RED.name)   # 輸出: RED
print(Color.RED.value)  # 輸出: 1

# 比較枚舉值
print(Color.RED == Color.GREEN)  # 輸出: False

# 迭代枚舉值
for color in Color:
    print(color)

# 轉換枚舉值為字串
print(str(Color.BLUE))  # 輸出: 'Color.BLUE'