python - 如何禁用 python 枚举中的某些项目,但不删除它们

标签 python filter enums items

我有一个枚举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

我需要隐藏 ANDROIDIOS 调用 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/

相关文章:

java - 从枚举值中获取枚举名称

python - 这些函数的结构有什么区别?

python - 强制额外的列显示在 pandas 数据透视表中?

python - 将多个掩码应用于数组

javascript - 将 jQuery 代码转换为 Mootools

swift - 像在 Java 中一样在 Swift 2 中编写一个简单的枚举

c - 避免误报 -Wswitch 警告

python - 在 Numpy 中将向量附加到矩阵的优雅解决方案?

python - 在Python中从列表中的每个元素减去自身的有效方法

Git:显示修改给定文件的提交的完整日志(或差异)