python - 如何比较 Python 中的枚举?

标签 python python-3.x enums compare

从 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/

相关文章:

python - OpenSSL:错误:1409442E:SSL 例程:ssl3_read_bytes:tlsv1 警报协议(protocol)版本

python - Pycairo 比例失真

kotlin - 交叉引用时枚举值变为空。如何解决这个问题?

python - Selenium Python Firefox webdriver : can't modify profile

python - 更改 Django/Postgres db_table 名称

python - 从 pandas DataFrame 定义 pyomo 中的参数

Python tkinter Entry() 不向变量返回任何值

python - 用 BeautifulSoup 刮掉多页

java - 将 enum 分成 2 个不同的 HashMap

java - Java 中的枚举可以有带不等号的名称吗?