I have the following code:
JavaScript
x
12
12
1
from enum import Enum
2
3
class BetterChoices(Enum):
4
@classmethod
5
def choices(cls):
6
return [(tag.name, tag.value) for tag in cls]
7
8
9
class SensorStatus(BetterChoices):
10
UNASSIGNED = 'Sin asignar'
11
ASSIGNED = 'Asignado'
12
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:
JavaScript
1
3
1
def __str__(self):
2
return self.name
3
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__
.