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

问题描述 投票:54回答:2

我有以下enum定义

from enum import Enum


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


print(D.x)

现在印刷的价值是

D.x

相反,我希望枚举的价值是印刷品

1

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

python python-3.x enums python-3.4
2个回答
117
投票

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

print(D.x.value)

Programmatic access to enumeration members and their attributes section

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

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

4
投票

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

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

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

现在我可以做到

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

如果你想打印self.name而不是x,你也可以使用1

© www.soinside.com 2019 - 2024. All rights reserved.