I have a class like the one below.
from enum import Enum, unique
from typing import Tuple
@unique
class Test(Enum):
v1: Tuple = (1, "value_1")
v2: Tuple = (2, "value_2")
def __init__(self, value_number, value_name) -> None:
self.value_number = value_number
self.value_name = value_name
@classmethod
def get_value_name_by_value_number(cls, number: int) -> str:
for member in cls.__members__.values():
if member.value_number == number:
return member.value_name
else:
raise NotImplementedError()
if __name__ == '__main__':
name = Test.get_value_name_by_value_number(number=2)
print(name)
When I run the code, the output is correct. But I don’t understand why it’s working with no problem. As far as I know the __init__ method is called on the creation of an instance. The method I’m calling is classmethod and thus I’m not creating an object and calling it directly from the class. So the __init__ is not invoked. But how does my class know what member.value_number and member.value_name are?
>Solution :
When creating the Test class, the Enum internals will create all enum members and manually call your __init__ method:
enum_member.__init__(*args)
You’d think it’d just instantiate your class normally somewhere, but with how much weird magic goes on in the Enum implementation, it turns out that wouldn’t work.