python如何获取枚举的名称 [英] python how to get name of the enum
问题描述
我有这样的枚举
class testEnum(Enum):
Code_1 = "successful response"
Code_2 = "failure response"
然后我有一个采用枚举键名称的方法 Code_1
和枚举键值成功响应
作为输入。
Then I have a method that takes the enum key name Code_1
and enum key value successful response
as inputs.
如果我发送 testEnum.Code_1
,则解析为成功响应
而不是 Code_1
。
If I send testEnum.Code_1
then that resolves to successful response
and not Code_1
.
我在网上检查了一些建议使用 testEnum.Code_1.name
的文档,但是抛出了错误,说明枚举项不存在名称。
I checked some documentation online that suggests to use testEnum.Code_1.name
but that throws an error saing that 'name' doesn't exist for the enum item.
有人知道如何获取枚举键的名称吗?
Does anyone know how to get the name of the enum key ?
推荐答案
我怀疑发生的事情是您正在使用名为枚举。如果这样做,您会得到类似的信息
I suspect that what's happened is that you're using the outdated pip-installable library called enum. If you did, you'd get something like
>>> from enum import Enum
>>> class testEnum(Enum):
... Code_1 = "successful response"
... Code_2 = "failure response"
...
>>> testEnum.Code_1
'successful response'
>>> testEnum.Code_1.name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'name'
而 real 枚举(如果您使用的是现代Python,则可以是标准库中的 enum
,也可以是 enum34
反向移植(如果不是),您会看到
whereas with the "real" enum (either enum
in the standard library if you're using modern Python, or the enum34
backport if you're not), you'd see
>>> from enum import Enum
>>> class testEnum(Enum):
... Code_1 = "successful response"
... Code_2 = "failure response"
...
>>> testEnum.Code_1
<testEnum.Code_1: 'successful response'>
>>> testEnum.Code_1.name
'Code_1'
您可以通过键入 help(enum)
并查看是否看到 NAME /枚举/模块引用/ https://docs.python.org/3.6/library/enum (如您所愿),或者如果您使用的是 NAME /枚举-Python中强大的枚举类型支持较老的。
You can confirm this independently by typing help(enum)
and seeing whether you see "NAME / enum / MODULE REFERENCE / https://docs.python.org/3.6/library/enum" (as you should) or simply "NAME / enum - Robust enumerated type support in Python" if you're using the older one.
这篇关于python如何获取枚举的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!