gpt4 book ai didi

python - 使用 Enum 的定义顺序作为自然顺序

转载 作者:太空狗 更新时间:2023-10-30 00:48:03 26 4
gpt4 key购买 nike

我正在尝试创建一个 Enum 子类,其值使用它们的定义顺序作为它们的自然排序顺序,如下例所示:

@functools.total_ordering
class SelectionType(enum.Enum):
character = 'character'
word = 'word'
sentence = 'sentence'
paragraph = 'paragraph'

def __le__(self, other):
if not isinstance(other, SelectionType):
return NotImplemented

return self._positions[self] < self._positions[other]

SelectionType._positions = {x: i for i, x in enumerate(SelectionType)}

有没有更直接的方法来获取枚举值在其定义顺序中的位置,或者有更好的方法来做到这一点?

最佳答案

如果这是您经常需要的模式,或者如果值很重要且不能用数字替换,请制作一个您可以继承的自定义枚举:

import enum

class ByDefinitionOrderEnum(enum.Enum):

def __init__(self, *args):
try:
# attempt to initialize other parents in the hierarchy
super().__init__(*args)
except TypeError:
# ignore -- there are no other parents
pass
ordered = len(self.__class__.__members__) + 1
self._order = ordered

def __ge__(self, other):
if self.__class__ is other.__class__:
return self._order >= other._order
return NotImplemented

def __gt__(self, other):
if self.__class__ is other.__class__:
return self._order > other._order
return NotImplemented

def __le__(self, other):
if self.__class__ is other.__class__:
return self._order <= other._order
return NotImplemented

def __lt__(self, other):
if self.__class__ is other.__class__:
return self._order < other._order
return NotImplemented

这允许您保留任何其他值,同时仍然根据定义顺序排序。

class SelectionType(ByDefinitionOrderEnum):

character = 'character'
word = 'word'
sentence = 'sentence'
paragraph = 'paragraph'

并在使用中:

>>> SelectionType.word < SelectionType.sentence
True

>>> SelectionType.word.value < SelectionType.sentence.value
False

关于python - 使用 Enum 的定义顺序作为自然顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42369749/

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