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
It is perfectly normal to use an enum for indexing into an array. You don't have to specify each enum value, they will increment automatically by 1. Letting the compiler pick the values reduces the possibility of mistyping and creating a bug, but it deprives you of seeing the values, which might be useful in debugging.
You can't do that. A C enum is not much more than a bunch of constants. There's no type-safety or reflection that you might get in a C# or Java enum . Show activity on this post.
In Java 10 and later, you can conveniently create a non-modifiable List by passing the EnumSet . The order of the new list will be in the iterator order of the EnumSet . The iterator order of an EnumSet is the order in which the element objects of the enum were defined on that enum. Great insight in this answer!
auto() method, we can get the assigned integer value automatically by just using enum. auto() method. Automatically assign the integer value to the values of enum class attributes.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With