I have a class with list of class members (variabls), each assigned to its own value.
class PacketType:
HEARTBEAT = 0xF0
DEBUG = 0xFC
ECHO = 0xFF
@staticmethod
def get_name(value):
# Get variable name from value
# Print the variable in string format
return ???
If I call PacketType.get_name(0xF0), I’d like to get return as "HEARTBEAT".
Does python allow this, or is the only way to make list of if-elif for each possible value?
>Solution :
The below works. (But I dont understand why you want to have such thing)
class PacketType:
HEARTBEAT = 0xF0
DEBUG = 0xFC
ECHO = 0xFF
@staticmethod
def get_name(value):
for k, v in PacketType.__dict__.items():
if v == value:
return k
return None
print(PacketType.get_name(0xFF))
output
ECHO