What's the cleanest way to set up an enumeration in Python?
This question already has an answer here:
Enums were added in python 3.4 (docs). See PEP 0435 for details.
If you are on python 2.x, there exists a backport on pypi.
pip install enum34
Your usage example is most similar to the python enum's functional API:
>>> from enum import Enum
>>> MyEnum = Enum('MyEnum', 'APPLE BANANA WALRUS')
>>> MyEnum.BANANA
<MyEnum.BANANA: 2>
However, this is a more typical usage example:
class MyEnum(Enum):
apple = 1
banana = 2
walrus = 3
You can also use an IntEnum
if you need enum instances to compare equal with integers, but I don't recommend this unless there is a good reason you need that behaviour.
You can use this. Although slightly longer, much more readable and flexible.
from enum import Enum
class Fruits(Enum):
APPLE = 1
BANANA = 2
WALRUS = 3
Edit : Python 3.4
Using enumerate
In [4]: list(enumerate(('APPLE', 'BANANA', 'WALRUS'),1))
Out[4]: [(1, 'APPLE'), (2, 'BANANA'), (3, 'WALRUS')]
The answer by noob should've been like this
In [13]: from enum import Enum
In [14]: Fruit=Enum('Fruit', 'APPLE BANANA WALRUS')
enum values are distinct from integers.
In [15]: Fruit.APPLE
Out[15]: <Fruit.APPLE: 1>
In [16]: Fruit.BANANA
Out[16]: <Fruit.BANANA: 2>
In [17]: Fruit.WALRUS
Out[17]: <Fruit.WALRUS: 3>
As in your question using range is a better option.
In [18]: APPLE,BANANA,WALRUS=range(1,4)
链接地址: http://www.djcxy.com/p/91738.html
上一篇: Python中的枚举类