从 Python 3.4 开始,存在 Enum
类。
我正在编写一个程序,其中一些常量具有特定的顺序,我想知道哪种方式最适合比较它们:
class Information(Enum):
ValueOnly = 0
FirstDerivative = 1
SecondDerivative = 2
现在有一种方法,需要将Information
的给定information
与不同的枚举进行比较:
information = Information.FirstDerivative
print(value)
if information >= Information.FirstDerivative:
print(jacobian)
if information >= Information.SecondDerivative:
print(hessian)
直接比较不适用于枚举,所以有三种方法,我想知道哪种方法更受欢迎:
方法一:使用值(value)观:
if information.value >= Information.FirstDerivative.value:
...
方法 2:使用 IntEnum:
class Information(IntEnum):
...
方法 3:根本不使用枚举:
class Information:
ValueOnly = 0
FirstDerivative = 1
SecondDerivative = 2
每种方法都有效,方法 1 有点冗长,而方法 2 使用不推荐的 IntEnum 类,而方法 3 似乎是在添加 Enum 之前这样做的方式。
我倾向于使用方法 1,但我不确定。
感谢您的建议!
最佳答案
如果您想将富比较运算符与 Enum
一起使用,您应该始终实现它们。使用 functools.total_ordering
类装饰器,您只需要实现一个 __eq__
方法以及单个排序,例如__lt__
。由于 enum.Enum
已经实现了 __eq__
这变得更加容易:
>>> import enum
>>> from functools import total_ordering
>>> @total_ordering
... class Grade(enum.Enum):
... A = 5
... B = 4
... C = 3
... D = 2
... F = 1
... def __lt__(self, other):
... if self.__class__ is other.__class__:
... return self.value < other.value
... return NotImplemented
...
>>> Grade.A >= Grade.B
True
>>> Grade.A >= 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: Grade() >= int()
IntEnum
可能会发生可怕、可怕、可怕的事情。它主要是为了向后兼容而包含在内,枚举过去是通过子类化 int
来实现的。来自 docs :
For the vast majority of code, Enum is strongly recommended, since IntEnum breaks some semantic promises of an enumeration (by being comparable to integers, and thus by transitivity to other unrelated enumerations). It should be used only in special cases where there’s no other choice; for example, when integer constants are replaced with enumerations and backwards compatibility is required with code that still expects integers.
以下是您不想这样做的示例:
>>> class GradeNum(enum.IntEnum):
... A = 5
... B = 4
... C = 3
... D = 2
... F = 1
...
>>> class Suit(enum.IntEnum):
... spade = 4
... heart = 3
... diamond = 2
... club = 1
...
>>> GradeNum.A >= GradeNum.B
True
>>> GradeNum.A >= 3
True
>>> GradeNum.B == Suit.spade
True
>>>
关于python - 如何比较 Python 中的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39268052/