枚举-在字符串转换中获取枚举的值


108

我定义了以下枚举

from enum import Enum


class D(Enum):
    x = 1
    y = 2


print(D.x)

现在的印刷价值是

D.x

相反,我想打印枚举的值

1

可以做些什么来实现此功能?


1
我应该弄清楚访问参数,我知道Dxvalue的事情,我想要的是Dx字符串转换以返回值,如果问题不能使条件清楚,对不起。
Vaibhav Mishra 2014年

Answers:


188

您正在打印枚举对象.value如果只想打印该属性,请使用该属性:

print(D.x.value)

请参阅对枚举成员及其属性编程访问权限部分

如果您有枚举成员并需要其名称或值:

>>>
>>> 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

当我将其与整数值进行比较时,它将作为对象返回。例如:if D.x == 10: ...。我应该采用什么方法处理整数?
alper

@alper:完全一样;D.x是枚举对象,D.x.value是整数。如果必须让枚举值像整数一样使用,请使用IntEnumtype,其中每个元素都是的子类,int因此IntEnumD.x == 10可以使用。
马丁·彼得斯

我添加了 def __eq__(self, other): return int(self.value) == otherdef __int__(self): return int(self.value)但我仍然想.value在不使用比较的情况下使用
alper

@alper:__eq__other另一个枚举值时,该实现不起作用;D.x == D.yD.x.value == D.y.value例如,在正确的情况下将失败。听起来您想使用它IntEnum而不是Enum那里。
马丁·彼得斯

7

我使用以下方法实现了访问

class D(Enum):
    x = 1
    y = 2

    def __str__(self):
        return '%s' % self.value

现在我可以做

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

self.name如果您想打印x,也可以使用代替1


2
为什么将字符串格式化和self._value_return str(self.value)更直接。
马丁·彼得

1
我只是查看了源代码,这就是它的实现方式,但是您是对的,而且self.value更干净。
Vaibhav Mishra 2014年

3
单下划线属性在生成的枚举类的内部;最好坚持记录的属性(恰好是一个特殊的描述符,以便您仍可以将其value用作枚举类型的名称)。
马丁·彼得斯

@MartijnPieters同意
Vaibhav Mishra

0

我在搜索访问 Enum使用字符串的。我知道这不是这个特殊问题中要问的问题,但标题确实“建议”它。

要使用字符串获取枚举,可以执行以下操作:

from enum import Enum


class D(Enum):
    x = 1
    y = 2


print(D["x"])  # <D.x: 1>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.