如何检查字符串枚举中是否存在字符串?

编程入门 行业动态 更新时间:2024-10-11 15:16:32
本文介绍了如何检查字符串枚举中是否存在字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我创建了以下枚举:

from enum import Enum class Action(str, Enum): NEW_CUSTOMER = "new_customer" LOGIN = "login" BLOCK = "block"

我也继承了 str ,所以我可以做以下事情:

I have inherited from str, too, so that I can do things such as:

action = "new_customer" ... if action == Action.NEW_CUSTOMER: ...

我现在希望能够检查此枚举中是否包含字符串,例如:

I would now like to be able to check if a string is in this Enum, such as:

if "new_customer" in Action: ....

我尝试将以下方法添加到该类中:

I have tried adding the following method to the class:

def __contains__(self, item): return item in [i for i in self]

但是,当我运行这段代码时:

However, when I run this code:

print("new_customer" in [i for i in Action]) print("new_customer" in Action)

我收到此异常:

True Traceback (most recent call last): File "/Users/kevinobrien/Documents/Projects/crazywall/utils.py", line 24, in <module> print("new_customer" in Action) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/enum.py", line 310, in __contains__ raise TypeError( TypeError: unsupported operand type(s) for 'in': 'str' and 'EnumMeta'

推荐答案

我今天碰到了这个问题;我不得不为Python 3.8更改了许多子包.

I just bumped into this problem today; I had to change a number of subpackages for Python 3.8.

以下是一种替代其他解决方案的方法,其灵感来自于此处的一个类似问题的出色答案,以及@MadPhysicist的此页面上的答案:

Perhaps an alternative to the other solutions here is the following, inspired by the excellent answer here to a similar question, as well as @MadPhysicist's answer on this page:

class MetaEnum(EnumMeta): def __contains__(cls, item): try: cls(item) except ValueError: return False return True class BaseEnum(Enum, metaclass=MetaEnum): pass class Stuff(BaseEnum): foo = 1 bar = 5

测试(在py37或38中):

Tests (either in py37 or 38):

>>> 1 in Stuff True >>> Stuff.foo in Stuff True >>> 2 in Stuff False >>> 2.3 in Stuff False >>> 'zero' in Stuff False

更多推荐

如何检查字符串枚举中是否存在字符串?

本文发布于:2023-11-12 13:32:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581643.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   是否存在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!