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

How can I disable some item in python Enum, but not remove them

我有一个枚举 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.[=17=中移除它们]

您可以创建排除枚举列表

class OsTypeEnum(Enum):
    WINDOWS = 100
    LINUX = 200
    MAC = 300
    ANDROID = 400
    IOS = 500

    @classmethod
    def get_list(cls):
        ret = []
        for e in cls:
            if e not in cls.__get_excluded():
                ret.append({'name': e.name, 'value': e.value})
        return ret

    @classmethod
    def __get_excluded(cls):
        return [cls.ANDROID, cls.IOS]

这似乎很适合 if 语句。 if 枚举不是 ANDROIDIOS,然后将其添加到 return 值。

与其对要排除的成员列表进行硬编码,不如将该信息作为每个成员的一部分。我将展示使用 aenum1 的代码,但它可以使用 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, the enum34 backport, and the Advanced Enumeration (aenum) 库的作者。