如何在python中取回枚举元素的名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29880323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get back name of the enum element in python?
提问by Mike
I have an enum defined like this:
我有一个像这样定义的枚举:
def enum(**enums):
return type('Enum', (), enums)
Status = enum(
STATUS_OK=0,
STATUS_ERR_NULL_POINTER=1,
STATUS_ERR_INVALID_PARAMETER=2)
I have a function that returns status as Status
enum.
How can I get the name of the enum value, and not just value?
我有一个将状态返回为Status
枚举的函数。如何获取枚举值的名称,而不仅仅是值?
>>> cur_status = get_Status()
>>> print(cur_status)
1
I would like to get STATUS_ERR_NULL_POINTER
, instead of 1
我想得到STATUS_ERR_NULL_POINTER
,而不是1
回答by Martijn Pieters
You'd have to loop through the class attributes to find the matching name:
您必须遍历类属性才能找到匹配的名称:
name = next(name for name, value in vars(Status).items() if value == 1)
The generator expression loops over the attributes and their values (taken from the dictionary produced by the vars()
function) then returns the first one that matches the value 1
.
生成器表达式循环遍历属性及其值(取自vars()
函数生成的字典),然后返回与值匹配的第一个1
。
Enumerations are better modelled by the enum
library, available in Python 3.4 or as a backport for earlier versions:
枚举由enum
库更好地建模,可在 Python 3.4 中使用或作为早期版本的反向移植:
from enum import Enum
class Status(Enum):
STATUS_OK = 0
STATUS_ERR_NULL_POINTER = 1
STATUS_ERR_INVALID_PARAMETER = 2
giving you access to the name and value:
使您可以访问名称和值:
name = Status(1).name # gives 'STATUS_ERR_NULL_POINTER'
value = Status.STATUS_ERR_NULL_POINTER.value # gives 1
回答by techneer
You don't need to loop through the Enum class but just access _member_map_.
您不需要遍历 Enum 类,而只需访问 _member_map_。
>>> Status._member_map_['STATUS_OK']
<Status.STATUS_OK: 0>