枚举-在字符串转换中获取枚举的值 [英] enum - getting value of enum on string conversion
本文介绍了枚举-在字符串转换中获取枚举的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我定义了以下枚举
from enum import Enum
class D(Enum):
x = 1
y = 2
print(D.x)
现在打印的值是
D.x
相反,我希望打印枚举的值
instead I wanted the enum's value to be print
1
可以做什么来实现此功能?
Hhat can be done to achieve this functionality?
推荐答案
您正在打印枚举 object 。如果只想打印以下内容,请使用 .value
属性:
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
您可以添加 __ str __
方法用于枚举,如果您想要的只是提供自定义字符串表示形式:
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
演示:
>>> 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
这篇关于枚举-在字符串转换中获取枚举的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文