Using Enum item as a list index

2020-07-23 05:27发布

I Have this piece of code :

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

I wonder what I should add if I want to perform this: random_array[FileType.MIMIKATZ]. Currently, Python3 tells me TypeError: list indices must be integers or slices, not FileType

1条回答
孤傲高冷的网名
2楼-- · 2020-07-23 06:04

Your class should inherit from IntEnum instead, this supports integer like behaviour. From the docs,

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

You can now use an enum constant to index your list,

data = [1, 2, 3, 4]
data[FileType.MIMIKATZ]
# 4
查看更多
登录 后发表回答