我定义了以下枚举
from enum import Enum
class D(Enum):
x = 1
y = 2
print(D.x)
现在的打印值(value)是
D.x
相反,我想打印枚举的值
1
要实现此功能可以做些什么?
最佳答案
您正在打印枚举对象。如果只想打印该属性,请使用.value
属性:
print(D.x.value)
参见Programmatic access to enumeration members and their attributes section:
如果您只想提供自定义字符串表示形式,则可以在枚举中添加
__str__
方法:class D(Enum):
def __str__(self):
return str(self.value)
x = 1
y = 2
演示:
>>> from enum import Enum
>>> class D(Enum):
... def __str__(self):
... return str(self.value)
... x = 1
... y = 2
...
>>> D.x
<D.x: 1>
>>> print(D.x)
1
关于python - 枚举-在字符串转换中获取枚举的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24487405/