I have the following code:
from enum import Enum class BetterChoices(Enum): @classmethod def choices(cls): return [(tag.name, tag.value) for tag in cls] class SensorStatus(BetterChoices): UNASSIGNED = 'Sin asignar' ASSIGNED = 'Asignado'
If I do print(SensorStatus.ASSIGNED.name)
it returns SensorStatus.ASSIGNED
. If I do print(SensorStatus.ASSIGNED.value)
it returns 'Sin asignar'
. What if I just want to return the name, not the Class.name
?
So, if I do print(x)
it will return ASSIGNED
as a string.
Advertisement
Answer
You can do that by implementing the __str__
magic method in your BetterChoices
class:
def __str__(self): return self.name
Each python object has string representation. When you do str(object)
or print(object)
Python implicitly calls object.__str__
. Enum
‘s default string representation has form <Classname>.<Attribute>
. To override that you just need implement your own version of __str__
.