> For the complete documentation index, see [llms.txt](https://l1nwatch.gitbook.io/interview_exercise/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://l1nwatch.gitbook.io/interview_exercise/stackoverflow-about-python/mei-ju-lei-xing-de-shi-yong.md).

# 枚举类型的使用?

PEP435 标准已经把枚举添加到 Python3.4 版本，在 PyPi 中也可以向后支持，通过：

```python
pip install enum34
```

如果下载 `enum` 没有数字将会是另一个版本

```python
from enum import Enum
animal = Enum("Animal", "ant bee cat dog")
```

等价于：

```python
class Animals(Enum):
    ant = 1
    bee = 2
    cat = 3
    dog = 4
```

在更早以前，有这些方法：

```python
def enum(**enums):
    return type('Enum', (), enums)

>>> Numbers = enum(ONE=1, TWO=2, THREE='three')
>>> Numbers.ONE
1
>>> Numbers.TWO
2
>>> Numbers.THREE
'three'
```

或者

```python
def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    return type('Enum', (), enums)

>>> Numbers = enum('ZERO', 'ONE', 'TWO')
>>> Numbers.ZERO
0
>>> Numbers.ONE
1
```

把值转换为名字：

```python
def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    reverse = dict((value, key) for key, value in enums.iteritems())
    enums['reverse_mapping'] = reverse
    return type('Enum', (), enums)
>>> Numbers.reverse_mapping['three']
'THREE'
```

这样会覆盖名字下的所有东西，但是对于枚举的输出很有用。如果转换的值不存在就会抛出 KeyError 异常


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://l1nwatch.gitbook.io/interview_exercise/stackoverflow-about-python/mei-ju-lei-xing-de-shi-yong.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
