我有一个这样的枚举
class testEnum(Enum):
Code_1 = "successful response"
Code_2 = "failure response"
然后我有一个方法将枚举键名 Code_1
和枚举键值 successful response
作为输入。
如果我发送 testEnum.Code_1
然后解析为 successful response
而不是 Code_1
。
我查看了一些建议使用 testEnum.Code_1.name
的在线文档,但会引发错误,指出枚举项不存在“名称”。
有谁知道如何获取枚举键的名称?
最佳答案
我怀疑发生的事情是您正在使用名为 enum 的过时的 pip 可安装库.如果你这样做了,你会得到类似的东西
>>> 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'
而使用“真正的”枚举(如果您使用的是现代 Python,则为标准库中的 enum
,否则为 enum34
backport),您会看到
>>> 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/enum/MODULE REFERENCE/https://docs.python.org/3.6/library/enum”(如您所愿)或只是“NAME/enum - Python 中强大的枚举类型支持”(如果您使用的是旧版)。
关于python如何获取枚举的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44446945/