【发布时间】:2017-01-09 03:11:13
【问题描述】:
从 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)
直接比较不适用于枚举,所以有三种方法,我想知道哪种方法更受欢迎:
方法一:使用价值观:
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,但我不确定。
感谢您的建议!
【问题讨论】:
-
您能引用“不推荐 IntEnum-class”吗? 3.7.1 的文档根本没有弃用它。
-
当然,来自文档:“对于大多数新代码,强烈建议使用 Enum 和 Flag,因为 IntEnum 和 IntFlag 破坏了枚举的一些语义承诺(通过与整数相比较,因此通过传递到其他不相关的枚举)。 IntEnum 和 IntFlag 应仅在 Enum 和 Flag 不起作用的情况下使用;例如,当整数常量被替换为枚举时,或者为了与其他系统的互操作性。”
-
方法 1 对我有用,谢谢!
标签: python python-3.x enums compare