Enum HOWTO

An Enum is a set of symbolic names bound to unique values. They are similar to global variables, but they offer a more useful repr(), grouping, type-safety, and a few other features.

They are most useful when you have a variable that can take one of a limited selection of values. For example, the days of the week:

>>> from enum import Enum
>>> class Weekday(Enum):
...     MONDAY = 1
...     TUESDAY = 2
...     WEDNESDAY = 3
...     THURSDAY = 4
...     FRIDAY = 5
...     SATURDAY = 6
...     SUNDAY = 7

Or perhaps the RGB primary colors:

>>> from enum import Enum
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3

As you can see, creating an Enum is as simple as writing a class that inherits from Enum itself.

備註

Case of Enum Members

Because Enums are used to represent constants, and to help avoid issues with name clashes between mixin-class methods/attributes and enum names, we strongly recommend using UPPER_CASE names for members, and will be using that style in our examples.

Depending on the nature of the enum a member's value may or may not be important, but either way that value can be used to get the corresponding member:

>>> Weekday(3)
<Weekday.WEDNESDAY: 3>

As you can see, the repr() of a member shows the enum name, the member name, and the value. The str() of a member shows only the enum name and member name:

>>> print(Weekday.THURSDAY)
Weekday.THURSDAY

The type of an enumeration member is the enum it belongs to:

>>> type(Weekday.MONDAY)
<enum 'Weekday'>
>>> isinstance(Weekday.FRIDAY, Weekday)
True>>> type(Weekday.MONDAY)
<enum 'Weekday'>
>>> isinstance(Weekday.FRIDAY, Weekday)
True

Enum members have an attribute that contains just their