python枚举字典中的元素,如何在python中获取枚举元素的名称?

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?

>>> cur_status = get_Status()

>>> print(cur_status)

1

I would like to get STATUS_ERR_NULL_POINTER, instead of 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.

Enumerations are better modelled by the enum library, available in Python 3.4 or as a backport for earlier versions:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值