以定义顺序迭代python枚举 [英] Iterate python Enum in definition order

查看:185
本文介绍了以定义顺序迭代python枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用python 3.4中带有python 2.7的backported枚举功能:

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

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

根据Enums的文档python 3( https://docs.python.org/3/library/enum.html #creation-an-enum ),枚举支持迭代,定义顺序 。然而,迭代不是为了我的事情:

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:

>>> 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的后缀版本中不支持然而?假设后者,是否有一个简单的方法强制它按顺序发生?

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?

推荐答案

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

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

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

这篇关于以定义顺序迭代python枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆