我有以下enum定义
from enum import Enum
class D(Enum):
x = 1
y = 2
print(D.x)
现在印刷的价值是
D.x
相反,我希望枚举的价值是印刷品
1
可以做些什么来实现这个功能?
您正在打印枚举对象。如果您只想打印它,请使用.value
属性:
print(D.x.value)
见Programmatic access to enumeration members and their attributes section:
如果您有枚举成员并且需要其名称或值:
>>> >>> member = Color.red >>> member.name 'red' >>> member.value 1
如果你想要的只是提供自定义字符串表示,你可以在你的枚举中添加一个__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
我使用以下方法实现了访问
class D(Enum):
x = 1
y = 2
def __str__(self):
return '%s' % self.value
现在我可以做到
print(D.x)
得到1
作为结果。
如果你想打印self.name
而不是x
,你也可以使用1
。