You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中比较字符串枚举?寻求更优实现方案

优化枚举类全序关系实现方案

你可以利用枚举类自带的特性避免手动重复列出枚举值,以下是两种简洁的实现方式:

方法一:使用Python 3.11+新增的_member_index_属性

Python 3.11为枚举成员添加了_member_index_属性,直接对应成员的声明顺序索引(从0开始),可直接用来比较顺序:

from enum import Enum
from functools import total_ordering

@total_ordering
class MyEnum(Enum):
    ONE = "one"
    TWO = "two"
    THREE = "three"

    def __eq__(self, other):
        if not isinstance(other, MyEnum):
            return False
        return self.value == other.value

    def __hash__(self):
        return hash(self.value)

    def __le__(self, other):
        if not isinstance(other, MyEnum):
            return False
        return self._member_index_ <= other._member_index_

方法二:兼容Python 3.7+的手动索引映射

如果你的Python版本低于3.11,可以在类初始化时自动生成成员到声明顺序索引的映射,无需手动枚举值:

from enum import Enum
from functools import total_ordering

@total_ordering
class MyEnum(Enum):
    ONE = "one"
    TWO = "two"
    THREE = "three"

    # 类加载时自动生成成员与声明顺序索引的映射
    _member_order = {member: idx for idx, member in enumerate(__members__.values())}

    def __eq__(self, other):
        if not isinstance(other, MyEnum):
            return False
        return self.value == other.value

    def __hash__(self):
        return hash(self.value)

    def __le__(self, other):
        if not isinstance(other, MyEnum):
            return False
        return self._member_order[self] <= self._member_order[other]

优势说明

  • 两种方式都无需手动维护枚举值到数字的映射,避免重复代码和出错风险
  • 完全基于枚举的声明顺序进行比较,符合你的需求
  • 保留了枚举值为字符串的设定,同时实现了全序关系

内容的提问来源于stack exchange,提问作者ivaigult

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 23:59:52