请注意,其中
Enum有一个名为的成员
_value2member_map_(未记录,在将来的python版本中可能会更改/删除):
print(Fruit._value2member_map_)# {4: <Fruit.Apple: 4>, 5: <Fruit.Orange: 5>, 6: <Fruit.Pear: 6>}
您可以
Enum根据此地图测试您的值是否在其中:
变体25 in Fruit._value2member_map_ # True7 in Fruit._value2member_map_ # False
如果您不想依赖此功能,则可以选择以下方法:
values = [item.value for item in Fruit] # [4, 5, 6]
或(可能更好):使用
set; 该
in运营商将更加有效:
values = set(item.value for item in Fruit) # {4, 5, 6}
然后用
添加5 in values # True7 in values # False
has_value到您的课程
然后可以将其作为方法添加到您的类中:
测试钥匙class Fruit(Enum): Apple = 4 Orange = 5 Pear = 6 @classmethod def has_value(cls, value): return value in cls._value2member_map_print(Fruit.has_value(5)) # Trueprint(Fruit.has_value(7)) # False
如果您想测试名称(而不是值),我将使用
_member_names_:
'Apple' in Fruit._member_names_ # True'Mango' in Fruit._member_names_ # False
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)