我有一个枚举OsTypeEnum
:
class OsTypeEnum(Enum):
WINDOWS = 100
LINUX = 200
MAC = 300
ANDROID = 400
IOS = 500
@classmethod
def get_list(cls):
ret = []
for e in cls:
ret.append({'name': e.name, 'value': e.value})
return ret
我需要隐藏 ANDROID
和 IOS
调用 get_list
函数,但不想从 中删除它们OsTypeEnum
.
最佳答案
与其对要排除的成员列表进行硬编码,不如将该信息作为每个成员的一部分。我将使用 aenum
显示代码library1,但可以使用 stdlib 版本来完成,只是更冗长。
from aenum import Enum
class OsTypeEnum(Enum):
#
_init_ = 'value type'
#
WINDOWS = 100, 'pc'
LINUX = 200, 'pc'
MAC = 300, 'pc'
ANDROID = 400, 'mobile'
IOS = 500, 'mobile'
#
@classmethod
def get_pc_list(cls):
ret = []
for e in cls:
if e.type == 'pc':
ret.append({'name': e.name, 'value': e.value})
return ret
#
@classmethod
def get_mobile_list(cls):
ret = []
for e in cls:
if e.type == 'mobile':
ret.append({'name': e.name, 'value': e.value})
return ret
通过存储有关成员的额外信息,您可以更轻松地获取原始列表以及其他列表。
在使用中,它看起来像:
>>> OsTypeEnum.get_pc_list()
[{'name': 'WINDOWS', 'value': 100}, {'name': 'LINUX', 'value': 200}, {'name': 'MAC', 'value': 300}]
>>> OsTypeEnum.get_mobile_list()
[{'name': 'ANDROID', 'value': 400}, {'name': 'IOS', 'value': 500}]
1 披露:我是 Python stdlib Enum
的作者, enum34
backport , 和 Advanced Enumeration (aenum
)图书馆。
关于python - 如何禁用 python 枚举中的某些项目,但不删除它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59368614/