如何在 Python 中表示“枚举"? [英] How can I represent an 'Enum' in Python?

查看:43
本文介绍了如何在 Python 中表示“枚举"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要是 C# 开发人员,但我目前正在使用 Python 开发一个项目.

如何在 Python 中表示等效的 Enum?

解决方案

枚举 已添加到 Python 3.4,如 PEP 435 中所述.它也已反向移植到 3.3、3.2、3.1、2.7、2.6、2.5 和 2.4皮皮.

要获得更高级的枚举技术,请尝试aenum 库(2.7、3.3+,与作者相同)enum34.代码在 py2 和 py3 之间并不完全兼容,例如你需要 __order__在python 2中).

  • 要使用enum34,请执行$ pip install enum34
  • 要使用aenum,请执行$ pip install aenum

安装 enum(无数字)将安装一个完全不同且不兼容的版本.


from enum import Enum # for enum34,或 stdlib 版本# from aenum import Enum # 为 aenum 版本Animal = Enum('Animal', 'ant bee cat dog')Animal.ant # 返回 <Animal.ant: 1>Animal['ant'] # 返回 (字符串查找)Animal.ant.name # 返回 'ant'(反向查找)

或等效地:

类动物(枚举):蚂蚁 = 1蜜蜂 = 2猫 = 3狗 = 4


在早期版本中,完成枚举的一种方法是:

def enum(**enums):返回类型('枚举',(),枚举)

用法如下:

<预><代码>>>>Numbers = enum(ONE=1, TWO=2, THREE='three')>>>数字.ONE1>>>数字二2>>>数字三'三'

您还可以通过以下方式轻松支持自动枚举:

def enum(*sequential, **named):枚举 = dict(zip(sequential, range(len(sequential))), **named)返回类型('枚举',(),枚举)

并像这样使用:

<预><代码>>>>Numbers = enum('零', '一', '二')>>>数字.零0>>>数字.ONE1

可以通过这种方式添加将值转换回名称的支持:

def enum(*sequential, **named):枚举 = dict(zip(sequential, range(len(sequential))), **named)reverse = dict((value, key) for key, value in enums.iteritems())枚举['reverse_mapping'] = 反向返回类型('枚举',(),枚举)

这会覆盖具有该名称的任何内容,但它对于在输出中呈现您的枚举很有用.如果反向映射不存在,它将抛出 KeyError.第一个例子:

<预><代码>>>>Numbers.reverse_mapping['三']'三'


如果您使用 MyPy 的另一种表达枚举"的方式使用 typing.Literal.

例如:

from typing import Literal #python >=3.8从typing_extensions 导入文字#python 2.7, 3.4-3.7Animal = Literal['ant', 'bee', 'cat', 'dog']def hello_animal(动物:动物):打印(f你好{动物}")hello_animal('rock') # 错误hello_animal('bee') # 通过

I'm mainly a C# developer, but I'm currently working on a project in Python.

How can I represent the equivalent of an Enum in Python?

解决方案

Enums have been added to Python 3.4 as described in PEP 435. It has also been backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4 on pypi.

For more advanced Enum techniques try the aenum library (2.7, 3.3+, same author as enum34. Code is not perfectly compatible between py2 and py3, e.g. you'll need __order__ in python 2).

  • To use enum34, do $ pip install enum34
  • To use aenum, do $ pip install aenum

Installing enum (no numbers) will install a completely different and incompatible version.


from enum import Enum     # for enum34, or the stdlib version
# from aenum import Enum  # for the aenum version
Animal = Enum('Animal', 'ant bee cat dog')

Animal.ant  # returns <Animal.ant: 1>
Animal['ant']  # returns <Animal.ant: 1> (string lookup)
Animal.ant.name  # returns 'ant' (inverse lookup)

or equivalently:

class Animal(Enum):
    ant = 1
    bee = 2
    cat = 3
    dog = 4


In earlier versions, one way of accomplishing enums is:

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

which is used like so:

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

You can also easily support automatic enumeration with something like this:

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

and used like so:

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

Support for converting the values back to names can be added this way:

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)

This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw a KeyError if the reverse mapping doesn't exist. With the first example:

>>> Numbers.reverse_mapping['three']
'THREE'


If you are using MyPy another way to express "enums" is with typing.Literal.

For example:

from typing import Literal #python >=3.8
from typing_extensions import Literal #python 2.7, 3.4-3.7


Animal = Literal['ant', 'bee', 'cat', 'dog']

def hello_animal(animal: Animal):
    print(f"hello {animal}")

hello_animal('rock') # error
hello_animal('bee') # passes

这篇关于如何在 Python 中表示“枚举"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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