按定义顺序迭代python Enum

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25982212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:54:42  来源:igfitidea点击:

Iterate python Enum in definition order

pythonpython-2.7enums

提问by Troy

I'm using the backported Enum functionality from python 3.4 with python 2.7:

我正在使用 python 3.4 和 python 2.7 的反向移植 Enum 功能:

> python --version
Python 2.7.6
> pip install enum34
# Installs version 1.0...

According to the documentation for Enums in python 3 (https://docs.python.org/3/library/enum.html#creating-an-enum), "Enumerations support iteration, in definition order". However, iteration is not happening in order for me:

根据 Python 3 中 Enums 的文档(https://docs.python.org/3/library/enum.html#creating-an-enum),“枚举支持迭代,按定义顺序”。但是,对我来说,迭代并没有发生:

>>> from enum import Enum
>>> class Shake(Enum):
...     vanilla = 7
...     chocolate = 4
...     cookies = 9
...     mint = 3
...     
>>> for s in Shake:
...     print(s)
...     
Shake.mint
Shake.chocolate
Shake.vanilla
Shake.cookies

Am I misunderstanding something, or is iteration in definition order just not supported in the backported versions of Enums yet? Assuming the latter, is there an easy way to force it to happen in order?

我是不是误解了什么,还是 Enums 的向后移植版本不支持按定义顺序进行迭代?假设是后者,是否有一种简单的方法可以强制它按顺序发生?

采纳答案by Troy

I found the answer here: https://pypi.python.org/pypi/enum34/1.0.

我在这里找到了答案:https: //pypi.python.org/pypi/enum34/1.0

For python <3.0, you need to specify an __order__ attribute:

对于 python <3.0,你需要指定一个 __order__ 属性:

>>> from enum import Enum
>>> class Shake(Enum):
...     __order__ = 'vanilla chocolate cookies mint'
...     vanilla = 7
...     chocolate = 4
...     cookies = 9
...     mint = 3
...     
>>> for s in Shake:
...     print(s)
...     
Shake.vanilla
Shake.chocolate
Shake.cookies
Shake.mint