Python enum - 在字符串转换时获取 enum 的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24487405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
enum - getting value of enum on string conversion
提问by Vaibhav Mishra
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
Hhat can be done to achieve this functionality?
可以做些什么来实现这个功能?
采纳答案by Martijn Pieters
You are printing the enum object. Use the .value
attribute if you wanted just to print that:
您正在打印枚举对象。.value
如果您只想打印该属性,请使用该属性:
print(D.x.value)
See the Programmatic access to enumeration members and their attributessection:
If you have an enum member and need its name or value:
>>> >>> member = Color.red >>> member.name 'red' >>> member.value 1
如果您有枚举成员并需要其名称或值:
>>> >>> 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:
__str__
如果您只想提供自定义字符串表示形式,则可以向枚举添加一个方法:
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
<D.x: 1>
>>> print(D.x)
1
回答by Vaibhav Mishra
I implemented access using the following
我使用以下方法实现了访问
class D(Enum):
x = 1
y = 2
def __str__(self):
return '%s' % self.value
now I can just do
现在我可以做
print(D.x)
to get 1
as result.
print(D.x)
得到1
结果。
You can also use self.name
in case you wanted to print x
instead of 1
.
您还可以使用self.name
的情况下,你想打印x
代替1
。