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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:40:30  来源:igfitidea点击:

enum - getting value of enum on string conversion

pythonpython-3.xenumspython-3.4

提问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 .valueattribute 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 1as result.

print(D.x)得到1结果。

You can also use self.namein case you wanted to print xinstead of 1.

您还可以使用self.name的情况下,你想打印x代替1