使用Enum项目作为列表索引 [英] Using Enum item as a list index
问题描述
我有这段代码:
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:列表索引必须是整数或切片,而不是FileType
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
推荐答案
您的类应该继承自> IntEnum
相反,它支持像行为这样的整数。在文档中,
Your class should inherit from IntEnum
instead, this supports integer like behaviour. From the docs,
IntEnum
的成员可以与整数进行比较;通过扩展,也可以将不同类型的
整数枚举与其他每个
进行比较:
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
这篇关于使用Enum项目作为列表索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!