Python 3 Enum


Author: yifei / Created: June 8, 2017, 12:31 a.m. / Modified: June 8, 2017, 1:22 a.m. / Edit

Basic Usage

>>> from enum import Enum
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3
...
>>> print(Color.RED)
Color.RED
>>> type(Color.RED)
<enum 'Color'>
>>> isinstance(Color.GREEN, Color)
True
>>> for color in Color:
...     print color
...
Color.RED
Color.GREEN
Color.BLUE

>>> Color(1)
<Color.RED: 1>
>>> Color['RED']
<Color.RED: 1>

>>> red = Color.RED
>>> red.name
'RED'
>>> red.value
1

Note Even though we use the class syntax to create Enums, Enums are not normal Python classes. See How are Enums different? for more details.

keeping unique value

use the enum.unique decorator

>>> from enum import Enum, unique
>>> @unique
... class Mistake(Enum):
...     ONE = 1
...     TWO = 2
...     THREE = 3
...     FOUR = 3
...
Traceback (most recent call last):
...
ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE

comparison

note that, enum.Enum is not int, use enum.IntEnum if you want your enum to be a integer

>>> Color.RED is Color.RED
True
>>> Color.RED is Color.BLUE
False
>>> Color.RED < Color.BLUE
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'Color' and 'Color'
>>> class IntColor(IntEnum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3
...
>>> IntColor.RED < IntColor.GREEN
True

subclass

Subclassing an enumeration is allowed only if the enumeration does not define any members.

functional

>>> Color = Enum('Color', 'RED GREEN BLUE')

IntFlag and Flag

>>> from enum import IntFlag
>>> class Perm(IntFlag):
...     R = 4
...     W = 2
...     X = 1
...
>>> Perm.R | Perm.W
<Perm.R|W: 6>
>>> Perm.R + Perm.W
6
>>> RW = Perm.R | Perm.W
>>> Perm.R in RW
True

评论区