简体   繁体   English

从多个值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

raise ValueError("%s is not a valid %s" % (value, cls. name )) raise ValueError("%s 不是一个有效的 %s" % (value, cls.name ))

ValueError: 8 is not a valid DataType ValueError: 8 不是有效的数据类型

ValueError: f is not a valid DataType ValueError:f 不是有效的数据类型

Is there a way to make this?有没有办法做到这一点? Or am I using the wrong data structure?还是我使用了错误的数据结构?

The easiest way is to use the aenum library 1 , which would look like this:最简单的方法是使用aenum1 ,它看起来像这样:

from aenum import MultiValueEnum

class DType(MultiValueEnum):
    float32 = "f", 8
    double64 = "d", 9

and in use:并在使用中:

>>> DType("f")
<DType.float32: 'f'>

>>> DType(9)
<DType.double64: 'd'>

As you can see, the first value listed is the canonical value, and shows up in the repr() .如您所见,列出的第一个值是规范值,并显示在repr()中。

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 ):如果您希望显示所有可能的值,或者需要使用 stdlib Enum (Python 3.4+),那么这里找到的答案就是您想要的基础(并且也适用于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]),
                )

and in use:并在使用中:

>>> DType("f")
<DType.float32: 'f', 8>

>>> Dtype(9)
<DType.float32: 'd', 9>

1 Disclosure: I am the author of the Python stdlib Enum , the enum34 backport , and the Advanced Enumeration ( aenum ) library. 1披露:我是Python stdlib Enumenum34 backportAdvanced Enumeration ( aenum )库的作者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM