我是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])
答案 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