如何检查Python枚举中的项目顺序?

ret*_*ikt 5 python enums

我有一个enum.Enum子类:

class MyEnum(Enum):
    A = "apple"
    C = "cherry"
    B = "banana"
Run Code Online (Sandbox Code Playgroud)

并且我希望能够使用<>查看给定成员是否按定义顺序排在另一个成员之前或之后,因此我可以执行以下操作:

>>> MyEnum.A < MyEnum.B
True
>>> MyEnum.B >= MyEnum.C
True
>>> MyEnum.C < MyEnum.A
False
Run Code Online (Sandbox Code Playgroud)

基于值在枚举的定义中出现的位置,而不是枚举值本身。我知道枚举会保留顺序,但是无法找到最先出现的顺序。如何在Python 3.7中完成此操作?

san*_*ash 5

您需要重写比较运算符并以某种方式检查比较枚举成员的名称顺序。我发现_member_names_保留定义成员的顺序:

from enum import Enum
import functools


@functools.total_ordering
class MyEnum(Enum):
    A = "apple"
    C = "cherry"
    B = "banana"

    def __eq__(self, other):
        if isinstance(other, MyEnum):
            return (
                self._member_names_.index(self.name) ==
                self._member_names_.index(other.name)
            )
        return NotImplemented

    def __gt__(self, other):
        if isinstance(other, MyEnum):
            return (
                self._member_names_.index(self.name) >
                self._member_names_.index(other.name)
            )
        return NotImplemented


print(MyEnum.A < MyEnum.B)  # True
print(MyEnum.B >= MyEnum.C)  # True
print(MyEnum.C < MyEnum.A)  # False
Run Code Online (Sandbox Code Playgroud)