【发布时间】:2020-11-29 19:05:48
【问题描述】:
我创建了以下枚举:
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)
我得到了这个例外:
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'
【问题讨论】:
-
不,我已经证明我可以做类似
"new_customer" in [i for i in Action]的事情,但我想要更干净的事情,比如"new_customer" in Action。 -
我重新打开了这个问题。它是关于字符串的,并且不限制 try/catch
标签: python class oop enums overriding