惯用方法检查一个值是否在枚举内部
我想检查某些枚举的值集中是否存在一些字符串值。这是我要做的:
from enum import Enum
class Color(str, Enum):
RED = "red"
GREEN = "green"
YELLOW = "yellow"
s = "red"
# s = "blue"
if any(s == c.value for c in Color):
print(Color(s))
当我检查文档发现:
Enummeta Metaclass负责提供包含(), dir (), iter ()和其他允许一个人可以允许的方法用典型类失败的枚举类做事,例如list(color)或some_enum_var in Color
但我想要一些不同的东西(检查存在 values )。是否有一种解决这个问题的方法?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
3.12中
在Python 该构造函数,如果有匹配值,它将返回适当的枚举实例,否则
valueerror
否则。In Python 3.12 you'll be able to do this directly with
in
:While we're waiting for that, though, one option in addition to the one you've already found is to pass your value to the constructor, which will return the appropriate enum instance if there's a matching value, and raise
ValueError
otherwise.您可以针对
_value2member_map _
测试值,如果您不希望用enum enum sub-class,将值映射到成员类> try-except 块:
You can test values against
_value2member_map_
, a dict attribute of theEnum
sub-class that maps values to member classes, if you prefer not to clutter up your code with atry-except
block:这是基于 blhsing 的答案:
Here is a slightly more aesthetic implementation based on blhsing's answer:
只需将其转换为价值清单并检查
Just convert it into value list and check