from enum import Enum
class Fruit(Enum):
Apple = 4
Orange = 5
Pear = 6
@staticmethod
def has_value(item):
return item in [v.value for v in Fruit.__members__.values()]
from enum import IntEnum
class Fruit(IntEnum):
Apple = 4
Orange = 5
Pear = 6
>>> 6 in Fruit.__members__.values()
True
>>> 7 in Fruit.__members__.values()
False
Enum + 列表内涵 + .value
如果你必须/想要坚持 Enum,你可以这样做:
>>> 6 in [f.value for f in Fruit]
True
>>> 7 in [f.value for f in Fruit]
False
import enum
class MyEnumMeta(enum.EnumMeta):
def __contains__(cls, item):
return item in [v.value for v in cls.__members__.values()]
class MyEnum(enum.Enum, metaclass=MyEnumMeta):
FOO = "foo"
BAR = "bar"
现在你可以做一个简单的检查:
>>> "foo" in MyEnum
True
如果所有枚举的值总是相同的类型,那么它甚至可以变得更简单——例如字符串:
import enum
class MyEnumMeta(enum.EnumMeta):
def __contains__(cls, item):
return item in cls.__members__.values()
class MyEnum(str, enum.Enum, metaclass=MyEnumMeta):
FOO = "foo"
BAR = "bar"
编辑: 另一个版本,技术上最正确的版本:
import enum
class MyEnumMeta(enum.EnumMeta):
def __contains__(cls, item):
try:
cls(item)
except ValueError:
return False
else:
return True
class MyEnum(enum.Enum, metaclass=MyEnumMeta):
FOO = "foo"
BAR = "bar"
class MyEnumMixin:
raw_values = None # for IDE autocomplete
def __new__(cls, value):
if 'raw_values' not in cls.__dict__:
cls.raw_values = set()
cls.raw_values.add(value)
if cls.__bases__[0] is MyEnumMixin:
member = object().__new__(cls)
else:
member = super().__new__(cls, value)
member._value_ = value
return member
class MyEnum(MyEnumMixin, Enum):
FOO = 1
BAR = 'bar'
print(1 in MyEnum.raw_values)
print('bar' in MyEnum.raw_values)
class MyStrEnumMixin(MyEnumMixin, str):
pass
class MyStrEnum(MyStrEnumMixin, Enum):
FOO = 'foo'
BAR = 'bar'
print('foo' in MyStrEnum.raw_values)
print('bar' in MyStrEnum.raw_values)