使用枚举项作为列表索引

2024-09-30 07:22:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段代码:

class FileType(Enum):
    BASIC = 0
    BASIC_CORRUPTED = 1
    BASIC_SHITTY_END = 2
    MIMIKATZ = 3
    HASHCAT = 4

    def __eq__(self, v):
        """
        Override == in order to make `FileType.BASIC == 0` equals to True, etc.
        """
        return self.value == v if isinstance(v, int) else self.value == v.value

我想知道如果我想执行此操作,我应该添加什么:random_array[FileType.MIMIKATZ]。目前,Python3告诉我TypeError: list indices must be integers or slices, not FileType


Tags: to代码selfbasicvaluedefenumclass
1条回答
网友
1楼 · 发布于 2024-09-30 07:22:41

您的类应该从^{}继承,这支持类似整数的行为。从文件上看

Members of an IntEnum can be compared to integers; by extension, integer enumerations of different types can also be compared to each other:

from enum import IntEnum

class FileType(IntEnum):
    BASIC = 0
    BASIC_CORRUPTED = 1
    BASIC_SHITTY_END = 2
    MIMIKATZ = 3
    HASHCAT = 4

现在可以使用enum常量来索引列表

^{pr2}$

相关问题 更多 >

    热门问题