从 Python 3.4 开始,Enum
类存在。
我正在编写一个程序,其中一些常量具有特定的顺序,我想知道哪种方式最适合比较它们:
class Information(Enum):
ValueOnly = 0
FirstDerivative = 1
SecondDerivative = 2
现在有一种方法,需要比较给定的information
of Information
使用不同的枚举:
information = Information.FirstDerivative
print(value)
if information >= Information.FirstDerivative:
print(jacobian)
if information >= Information.SecondDerivative:
print(hessian)
直接比较不适用于枚举,因此有三种方法,我想知道哪一种是首选:
方法 1:使用值:
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__
. Since 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 https://docs.python.org/3/library/enum.html#intenum:
对于绝大多数代码,强烈建议使用 Enum,因为
IntEnum 打破了枚举的一些语义承诺(通过
与整数可比较,因此通过与其他不相关的传递性
枚举)。它应该只在特殊情况下使用
没有其他选择;例如,当整数常量替换为
需要枚举和向后兼容的代码
仍然期望整数。
以下是您不想这样做的示例:
>>> 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
>>>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)