从多个值获取枚举名称python [英] Get Enum name from multiple values python
问题描述
我正在尝试使用多个值之一来获取枚举的名称:
I'm trying to get the name of a enum given one of its multiple values:
class DType(Enum):
float32 = ["f", 8]
double64 = ["d", 9]
当我尝试获取一个给出其工作名称的值时:
when I try to get one value giving the name it works:
print DType["float32"].value[1] # prints 8
print DType["float32"].value[0] # prints f
但是当我尝试从给定值中获取名称时,只会出现错误:
but when I try to get the name out of a given value only errors will come:
print DataType(8).name
print DataType("f").name
提高ValueError(%s不是有效的%s%(值,cls。名称))
ValueError: 8不是有效的数据类型
ValueError: 8 is not a valid DataType
ValueError:f不是有效的数据类型
ValueError: f is not a valid DataType
有没有办法做到这一点?还是我使用了错误的数据结构?
Is there a way to make this? or am I using the wrong data structure?
推荐答案
最简单的方法是使用 aenum
库 1 ,如下所示:
The easiest way is to use the aenum
library1, which would look like this:
from aenum import MultiValueEnum
class DType(MultiValueEnum):
float32 = "f", 8
double64 = "d", 9
并在使用中:
>>> DType("f")
<DType.float32: 'f'>
>>> DType(9)
<DType.double64: 'd'>
如您所见,列出的第一个值是规范值,并显示在 repr()
。
As you can see, the first value listed is the canonical value, and shows up in the repr()
.
如果希望显示所有可能的值,或者需要使用stdlib 枚举
(Python 3.4及更高版本),则在此处找到答案是您想要什么(也可以与 aenum
一起使用):
If you want all the possible values to show up, or need to use the stdlib Enum
(Python 3.4+), then the answer found here is the basis of what you want (and will also work with aenum
):
class DType(Enum):
float32 = "f", 8
double64 = "d", 9
def __new__(cls, *values):
obj = object.__new__(cls)
# first value is canonical value
obj._value_ = values[0]
for other_value in values[1:]:
cls._value2member_map_[other_value] = obj
obj._all_values = values
return obj
def __repr__(self):
return '<%s.%s: %s>' % (
self.__class__.__name__,
self._name_,
', '.join([repr(v) for v in self._all_values]),
)
并在使用中:
>>> DType("f")
<DType.float32: 'f', 8>
>>> Dtype(9)
<DType.float32: 'f', 9>
1 披露:我是 Python stdlib Enum
, enum34
移植,和高级枚举( aenum
)图书馆。
1 Disclosure: I am the author of the Python stdlib Enum
, the enum34
backport, and the Advanced Enumeration (aenum
) library.
这篇关于从多个值获取枚举名称python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!