gpt4 book ai didi

python - 在枚举中搜索值

转载 作者:行者123 更新时间:2023-12-01 08:04:31 25 4
gpt4 key购买 nike

我是Python新手。我正在尝试检查字符串是否具有枚举中定义的任何匹配值。例如,我想在下面的代码中打印“Found”

我添加了以下隐式方法的定义来支持比较、散列和获取方法


from enum import Enum


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'

def __hash__(self):
return hash(self.value)

def __str__(self):
return self.value

def __eq__(self, other):
if type(self) == type(other):
return self.value == other.value
return self.value == other

def __get__(self, *args, **kwargs):
return self.value


Map = {
States.ON_HOLD_STATE: [States.NEVER_RUN_STATE],
States.DISABLED_STATE: [States.NEVER_RUN_STATE],
States.RUNNING_STATE: [States.DEPENDENCY_WAIT_STATE,
States.ON_HOLD_STATE,
States.NEVER_RUN_STATE],
States.IGNORED_STATE: [States.RUNNING_STATE,
States.NEVER_RUN_STATE]
}


print(Map[States.RUNNING_STATE]) // ['dependency_wait', 'on_hold', 'never_run']
print(Map['running']) // ['dependency_wait', 'on_hold', 'never_run']
print(States.RUNNING_STATE == 'dependency_wait') // False
print(States.RUNNING_STATE == 'running') // True
print(States.RUNNING_STATE == States.RUNNING_STATE) // True

if 'running' in States:
print "Found" // Does not gets printed

if States.RUNNING_STATE in States:
print "Found here" // Does not gets printed

最佳答案

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

关于python - 在枚举中搜索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55598652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com