gpt4 book ai didi

python - 如何检查 Python 枚举中项目的排序?

转载 作者:行者123 更新时间:2023-12-04 19:25:28 24 4
gpt4 key购买 nike

我有一个 enum.Enum子类:

class MyEnum(Enum):
A = "apple"
C = "cherry"
B = "banana"

我希望能够使用 <>查看一个给定的成员在定义顺序中是在另一个成员之前还是之后,所以我可以做这样的事情:

>>> MyEnum.A < MyEnum.B
True
>>> MyEnum.B >= MyEnum.C
True
>>> MyEnum.C < MyEnum.A
False

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

最佳答案

您需要覆盖比较运算符并以某种方式检查比较枚举成员的名称顺序。我发现 _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

关于python - 如何检查 Python 枚举中项目的排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58362348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com