I have following enum defined
from enum import Enum
class D(Enum):
x = 1
y = 2
print(D.x)
now the printed value is
D.x
instead I wanted the enum's value to be print
1
what can be done to achieve this functionality.
解决方案
You are printing the enum object. Use the .value attribute if you wanted just to print that:
print(D.x.value)
If you have an enum member and need its name or value:
>>>
>>> member = Color.red
>>> member.name
'red'
>>> member.value
1
You could add a __str__ method to your enum, if all you wanted was to provide a custom string representation:
class D(Enum):
def __str__(self):
return str(self.value)
x = 1
y = 2
Demo:
>>> from enum import Enum
>>> class D(Enum):
... def __str__(self):
... return str(self.value)
... x = 1
... y = 2
...
>>> D.x
>>> print(D.x)
1