在 Python2中按照定义顺序迭代枚举

我使用的是 python 3.4与 python 2.7之间的后端 Enum 功能:

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

根据 python3(https://docs.python.org/3/library/enum.html#creating-an-enum)中的 Enums 文档,“ Enumerations support iteration,按照定义顺序”。然而,对我来说,重复并没有按顺序发生:

>>> 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

我是不是误解了什么,或者在 Enums 的后端版本中还不支持按照定义顺序进行迭代?假设是后者,有没有一种简单的方法来强迫它按顺序发生?

85507 次浏览

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

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

>>> 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

use

__order__

to define the order of enums for python version less than 3 . It is not necessary in python3 but make sure the order which is supplied same as declared order otherwise it will give error:

TypeError: member order does not match _order_




import enum




class EXCHANGE(enum.Enum):
__order__ = " EXCHANGE_NSE EXCHANGE_BSE EXCHANGE_NFO EXCHANGE_CDS EXCHANGE_BFO EXCHANGE_MCX EXCHANGE_BCD "
EXCHANGE_NSE = "NSE"
EXCHANGE_BSE = "BSE"
EXCHANGE_NFO = "NFO"
EXCHANGE_CDS = "CDS"
EXCHANGE_BFO = "BFO"
EXCHANGE_MCX = "MCX"
EXCHANGE_BCD = "BCD"




if __name__ == "__main__":
for ex in EXCHANGE:
print(f"{ex.name} : {ex.value}")

Output:

EXCHANGE_NSE : NSE
EXCHANGE_BSE : BSE
EXCHANGE_NFO : NFO
EXCHANGE_CDS : CDS
EXCHANGE_BFO : BFO
EXCHANGE_MCX : MCX
EXCHANGE_BCD : BCD