python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python枚举类enum

一文带你了解Python枚举类enum的使用

作者:XerCis

枚举是与多个唯一常量绑定的一组符号,因为枚举表示的是常量,建议枚举成员名用大写 IntEnum 便于进行系统交互。本文将通过一些示例代码讲解Python枚举类的使用,需要的可以参考一下

简介

枚举是与多个唯一常量绑定的一组符号

因为枚举表示的是常量,建议枚举成员名用大写

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'}

访问成员

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

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

官方教程

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的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文