自 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)
直接比较不适用于枚举,所以有三种方法,我想知道哪一种是首选:
方法 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,但我不确定。
感谢您的任何建议!
原文由 Sebastian Werk 发布,翻译遵循 CC BY-SA 4.0 许可协议
我之前没有遇到过枚举,所以我扫描了文档( https://docs.python.org/3/library/enum.html )……并找到了 OrderedEnum(第 8.13.13.2 节)这不是你想要的吗?从文档: