python – enum – 在字符串转换中获取枚举值
作者:互联网
我有以下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:
If you have an enum member and need its name or value:
06001
如果您只想提供自定义字符串表示形式,则可以在枚举中添加__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-3-4,python,python-3-x,enums 来源: https://codeday.me/bug/20190926/1821941.html