如何获取枚举元素的名称? [英] How to get back name of the enum element?

查看:78
本文介绍了如何获取枚举元素的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的枚举:

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)

我有一个将状态返回为 Status 枚举的函数.如何获得枚举值的名称,而不仅仅是值?

I have a function that returns status as Status enum. How can I get the name of the enum value, and not just value?

>>> cur_status = get_Status()
>>> print(cur_status)
1

我想获取 STATUS_ERR_NULL_POINTER ,而不是 1

推荐答案

您必须遍历类属性以找到匹配的名称:

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.

枚举更好地为枚举建模>,可在Python 3.4中使用,也可以作为向后移植到早期版本:

from enum import Enum

class Status(Enum):
    STATUS_OK = 0
    STATUS_ERR_NULL_POINTER = 1 
    STATUS_ERR_INVALID_PARAMETER = 2

允许您访问名称和值:

name = Status(1).name  # gives 'STATUS_ERR_NULL_POINTER'
value = Status.STATUS_ERR_NULL_POINTER.value  # gives 1

这篇关于如何获取枚举元素的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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