Python枚举 - 获取字符串转换的枚举值 [英] Python enum - getting value of enum on string conversion

查看:2572
本文介绍了Python枚举 - 获取字符串转换的枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下枚举定义

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

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

what can be done to achieve this functionality.

推荐答案

您正在打印枚举对象。如果您只想打印,请使用 .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

这篇关于Python枚举 - 获取字符串转换的枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆