Python Enum类成员资格

时间:2017-03-16 09:37:41

标签: python enums

当使用Python 3 Enum中引入的programmatically类时,程序员应如何检查给定整数的Enum成员资格?

显然,你可以ask for forgiveness,但是我是否有错过的会员制检查功能?更明确地说,我想取一个整数值并检查它的值是否对应于有效的枚举。

from enum import Enum

class TestEnum(Enum):
    a = 0
    b = 1
    c = 2

输出:

In [13]: TestEnum(0)
Out[13]: <TestEnum.a: 0>

In [14]: TestEnum(4)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-09c663e9e214> in <module>()
----> 1 TestEnum(4)

C:\Anaconda3\lib\enum.py in __call__(cls, value, names, module, qualname, type, start)
    239         """
    240         if names is None:  # simple value lookup
--> 241             return cls.__new__(cls, value)
    242         # otherwise, functional API: we're creating a new Enum type
    243         return cls._create_(value, names, module=module, qualname=qualname, type=type, start=start)

C:\Anaconda3\lib\enum.py in __new__(cls, value)
    474                 if member._value_ == value:
    475                     return member
--> 476         raise ValueError("%r is not a valid %s" % (value, cls.__name__))
    477
    478     def __repr__(self):

ValueError: 4 is not a valid TestEnum

3 个答案:

答案 0 :(得分:4)

Enum确实有一个__contains__方法,但它会检查成员名称而不是成员值:

def __contains__(cls, member):
    return isinstance(member, cls) and member._name_ in cls._member_map_

在内部(在CPython中),它们有一个私有属性,它将值映射到名称(但仅适用于可散列值):

>>> 2 in TestEnum._value2member_map_
True
>>> 3 in TestEnum._value2member_map_
False

但依赖私有属性并不是一个好主意,因为它们可以随时更改,因此您可以添加自己的循环__members__.values()的方法:

>>> class TestEnum(Enum):
...     a = 0
...     b = 1
...     c = 2
...
...     @classmethod
...     def check_value_exists(cls, value):
...         return value in (val.value for val in cls.__members__.values())
...

>>>
>>> TestEnum.check_value_exists(2)
True
>>> TestEnum.check_value_exists(3)
False

答案 1 :(得分:0)

你的意思是:

from enum import Enum

class TestEnum(Enum):
    a = 3
    b = 2
    c = 1


print(TestEnum.b.name,TestEnum.b.value)

print(TestEnum(2).name,TestEnum(2).value)

输出:

b 2

答案 2 :(得分:0)

    @classmethod
    def valueList(cls)->list:
        '''
        get my list of values
        
        Return:
            list: the list of values
        '''
        valueList=list(map(lambda c: c.value, cls))
        return valueList
 
    @classmethod
    def isValid(cls,value)->bool:
        '''
        check whether the given value is valid
        
        Args:
            value: the value to check
        
        Return:
            bool: True if the value is a valid value of this enum
        '''
        valueList=cls.valueList()
        return value in valueList