如何在不使用try / catch的情况下测试Python枚举中是否存在int值? [英] How do I test if int value exists in Python Enum without using try/catch?
问题描述
使用Python的Enum类,有没有办法在不使用try / catch的情况下测试Enum是否包含特定的int值?
Using the Python Enum class, is there a way to test if an Enum contains a specific int value without using try/catch?
使用以下类: / p>
With the following class:
from enum import Enum
class Fruit(Enum):
Apple = 4
Orange = 5
Pear = 6
如何测试值6(
推荐答案
测试值
变体1
请注意,枚举
的成员名为 _value2member_map _
(未记录,在以后的python版本中可能会更改/删除):
test for values
variant 1
note that an Enum
has a member called _value2member_map_
(which is undocumented and may be changed/removed in future python versions):
print(Fruit._value2member_map_)
# {4: <Fruit.Apple: 4>, 5: <Fruit.Orange: 5>, 6: <Fruit.Pear: 6>}
您可以针对此地图测试您的 Enum
中是否有值:
you can test if a value is in your Enum
against this map:
5 in Fruit._value2member_map_ # True
7 in Fruit._value2member_map_ # False
变体2
如果您不想依赖此功能,则可以选择:
variant 2
if you do not want to rely on this feature this is an alternative:
values = [item.value for item in Fruit] # [4, 5, 6]
或((可能更好) ):使用设置
; in
运算符将更有效:
or (probably better): use a set
; the in
operator will be more efficient:
values = set(item.value for item in Fruit) # {4, 5, 6}
然后用
then test with
5 in values # True
7 in values # False
向您的班级添加 has_value
将此方法添加到您的班级中:
add has_value
to your class
you could then add this as a method to your class:
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)) # True
print(Fruit.has_value(7)) # False
测试键
如果要测试名称(而不是值),我会使用 _member_names _
:
'Apple' in Fruit._member_names_ # True
'Mango' in Fruit._member_names_ # False
这篇关于如何在不使用try / catch的情况下测试Python枚举中是否存在int值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!