如何测试是否存在具有特定名称的Enum成员? [英] How to test if an Enum member with a certain name exists?
本文介绍了如何测试是否存在具有特定名称的Enum成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Python 3.4,我想测试Enum类是否包含具有特定名称的成员。
Using Python 3.4 I want to test whether an Enum class contains a member with a certain name.
示例:
class Constants(Enum):
One = 1
Two = 2
Three = 3
print(Constants['One'])
print(Constants['Four'])
给出:
Constants.One
File "C:\Python34\lib\enum.py", line 258, in __getitem__
return cls._member_map_[name]
KeyError: 'Four'
我可以捕获到 KeyError
并将异常作为存在的指示,但是也许还有一种更优雅的方式吗?
I could catch the KeyError
and take the exception as indication of existence but maybe there is a more elegant way?
推荐答案
您可以使用 Enum .__ members __
- 将名称映射到成员的有序词典 :
You could use Enum.__members__
- an ordered dictionary mapping names to members:
In [12]: 'One' in Constants.__members__
Out[12]: True
In [13]: 'Four' in Constants.__members__
Out[13]: False
这篇关于如何测试是否存在具有特定名称的Enum成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文