在枚举中寻找价值

时间:2019-04-09 17:59:33

标签: python python-2.7

我是python的新手。我正在尝试检查字符串是否在Enum中定义了任何匹配值。例如,我要在下面的代码中打印“找到”

我添加了以下隐式方法的定义,以支持比较,哈希和获取方法

array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0])

1 个答案:

答案 0 :(得分:1)

Enum的元类EnumMeta定义了__contains__魔术方法,以测试Enum实例是否为给定Enum类的成员仅基于成员的姓名而不是值,因此,如果希望它能够基于值测试成员资格,则必须使用迭代EnumMeta.__contains__的值的函数来覆盖_member_map_ dict属性,并将每个成员值与给定的测试值进行比较以实现以下目标:

from enum import Enum, EnumMeta

def custom_EnumMeta__contains__(cls, member):
    return isinstance(member, cls) and member.name in cls._member_map_ or \
        any(m._value_ == member for m in cls._member_map_.values())
EnumMeta.__contains__ = custom_EnumMeta__contains__

class States(Enum):
    COMPLETED_STATE = 'completed'
    DEPENDENCY_WAIT_STATE = 'dependency_wait'
    FAILED_NO_RERUN_STATE = 'failed_no_rerun'
    IGNORED_STATE = 'ignored'
    RUNNING_STATE = 'running'
    NEVER_RUN_STATE = 'never_run'
    ON_HOLD_STATE = 'on_hold'

if 'running' in States:
    print "Found"

if States.RUNNING_STATE in States:
    print "Found here"

这将输出:

Found
Found here