How to compare Enums in Python?(如何比较 Python 中的枚举?)
问题描述
从 Python 3.4 开始,存在 Enum
类.
Since Python 3.4, the Enum
class exists.
我正在编写一个程序,其中一些常量具有特定的顺序,我想知道哪种方式最适合比较它们:
I am writing a program, where some constants have a specific order and I wonder which way is the most pythonic to compare them:
class Information(Enum):
ValueOnly = 0
FirstDerivative = 1
SecondDerivative = 2
现在有一种方法,需要将Information
的给定information
与不同的枚举进行比较:
Now there is a method, which needs to compare a given information
of Information
with the different enums:
information = Information.FirstDerivative
print(value)
if information >= Information.FirstDerivative:
print(jacobian)
if information >= Information.SecondDerivative:
print(hessian)
直接比较不适用于枚举,所以有三种方法,我想知道哪种方法更受欢迎:
The direct comparison does not work with Enums, so there are three approaches and I wonder which one is preferred:
方法一:使用价值观:
if information.value >= Information.FirstDerivative.value:
...
方法 2:使用 IntEnum:
Approach 2: Use IntEnum:
class Information(IntEnum):
...
方法 3:根本不使用枚举:
Approach 3: Not using Enums at all:
class Information:
ValueOnly = 0
FirstDerivative = 1
SecondDerivative = 2
每种方法都有效,方法 1 有点冗长,而方法 2 使用不推荐的 IntEnum 类,而方法 3 似乎是在添加 Enum 之前这样做的方式.
Each approach works, Approach 1 is a bit more verbose, while Approach 2 uses the not recommended IntEnum-class, while and Approach 3 seems to be the way one did this before Enum was added.
我倾向于使用方法 1,但我不确定.
I tend to use Approach 1, but I am not sure.
感谢您的建议!
推荐答案
我之前没有遇到过 Enum,所以我扫描了文档(https://docs.python.org/3/library/enum.html) ... 并找到了 OrderedEnum(第 8.13.13.2 节)这不是你想要的吗?来自文档:
I hadn'r encountered Enum before so I scanned the doc (https://docs.python.org/3/library/enum.html) ... and found OrderedEnum (section 8.13.13.2) Isn't this what you want? From the doc:
>>> class Grade(OrderedEnum):
... A = 5
... B = 4
... C = 3
... D = 2
... F = 1
...
>>> Grade.C < Grade.A
True
这篇关于如何比较 Python 中的枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何比较 Python 中的枚举?


基础教程推荐
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01