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

标签 python class oop enums overriding

我创建了以下枚举:

from enum import Enum

class Action(str, Enum):
    NEW_CUSTOMER = "new_customer"
    LOGIN = "login"
    BLOCK = "block"
我继承自 str , 以便我可以做以下事情:
action = "new_customer"
...
if action == Action.NEW_CUSTOMER:
    ...
我现在希望能够检查字符串是否在此 Enum 中,例如:
if "new_customer" in Action:
    ....
我尝试将以下方法添加到类中:
def __contains__(self, item):
    return item in [i for i in self]
但是,当我运行此代码时:
print("new_customer" in [i for i in Action])
print("new_customer" in Action)
我得到这个异常(exception):
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 更改许多子包。
也许这里其他解决方案的替代方案如下,灵感来自优秀答案 here到一个类似的问题,以及@MadPhysicist 的 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 中):
>>> 1 in Stuff
True

>>> Stuff.foo in Stuff
True

>>> 2 in Stuff
False

>>> 2.3 in Stuff
False

>>> 'zero' in Stuff
False

关于python - 如何检查字符串枚举中是否存在字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63335753/

相关文章:

python - 如何处理从 python 函数返回的空(无)元组

javascript - 基于分配给它的特定 css 类的另一个 div #id 隐藏带有 css #id 的 div

php - 在类中使用数组遍历

oop - 如何在类构造函数参数中动态传递窗口小部件

Python/BS4 导航 'div class' 不适用于站点

python - 更新线程内的pyqtgraph BarGraphItem

ruby - Ruby 模块中的私有(private)类(不是类方法)?

java - 为什么继承深度在 GAE 上的 Datanucleus JDO 中很重要?

c# - 将一种形式的控件用于另一种形式

python - 旋转角色和 Sprite 墙