如何在python中将int转换为Enum?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23951641/
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 03:44:37  来源:igfitidea点击:

How to convert int to Enum in python?

pythonpython-2.7enumsinttype-conversion

提问by User

Using the new Enum feature (via backport enum34) with python 2.7.6.

在python 2.7.6 中使用新的 Enum 功能(通过向后移植 enum34)。

Given the following definition, how can I convert an int to the corresponding Enum value?

鉴于以下定义,如何将 int 转换为相应的 Enum 值?

from enum import Enum

class Fruit(Enum):
    Apple = 4
    Orange = 5
    Pear = 6

I know I can hand craft a series of if-statements to do the conversion but is there an easy pythonic way to convert? Basically, I'd like a function ConvertIntToFruit(int) that returns an enum value.

我知道我可以手工制作一系列 if 语句来进行转换,但是有没有一种简单的 Pythonic 转换方法?基本上,我想要一个返回枚举值的函数 ConvertIntToFruit(int)。

My use case is I have a csv file of records where I'm reading each record into an object. One of the file fields is an integer field that represents an enumeration. As I'm populating the object I'd like to convert that integer field from the file into the corresponding Enum value in the object.

我的用例是我有一个记录的 csv 文件,我将每条记录读入一个对象。文件字段之一是表示枚举的整数字段。在填充对象时,我想将文件中的整数字段转换为对象中相应的 Enum 值。

采纳答案by Martijn Pieters

You 'call' the Enumclass:

你“打电话”给Enum班级:

Fruit(5)

to turn 5into Fruit.Orange:

轮到5Fruit.Orange

>>> from enum import Enum
>>> class Fruit(Enum):
...     Apple = 4
...     Orange = 5
...     Pear = 6
... 
>>> Fruit(5)
<Fruit.Orange: 5>

From the Programmatic access to enumeration members and their attributessection of the documentation:

从文档的枚举成员及其属性部分的编程访问

Sometimes it's useful to access members in enumerations programmatically (i.e. situations where Color.redwon't do because the exact color is not known at program-writing time). Enumallows such access:

>>> Color(1)
<Color.red: 1>
>>> Color(3)
<Color.blue: 3>

有时以编程方式访问枚举中的成员很有用(即,Color.red由于在编写程序时不知道确切颜色而无法访问的情况)。Enum允许这样的访问:

>>> Color(1)
<Color.red: 1>
>>> Color(3)
<Color.blue: 3>

In a related note: to map a string value containing the nameof an enum member, use subscription:

在相关注释中:要映射包含枚举成员名称的字符串值,请使用订阅:

>>> s = 'Apple'
>>> Fruit[s]
<Fruit.Apple: 4>

回答by Ali Ezzat Odeh

I think it is in simple words is to convert the intvalue into Enumby calling EnumType(int_value), after that access the nameof the Enumobject:

我认为这是简单的话是对转换int价值为Enum通过调用EnumType(int_value),访问后name的的Enum对象:

my_fruit_from_int = Fruit(5) #convert to int
fruit_name = my_fruit_from_int.name #get the name
print(fruit_name) #Orange will be printed here

Or as a function:

或者作为一个函数:

def convert_int_to_fruit(int_value):
    try:
        my_fruit_from_int = Fruit(int_value)
        return my_fruit_from_int.name
    except:
        return None

回答by user3355323

I wanted something similar so that I could access either part of the value pair from a single reference. The vanilla version:

我想要类似的东西,以便我可以从单个引用访问值对的任一部分。香草版:

#!/usr/bin/env python3


from enum import IntEnum


class EnumDemo(IntEnum):
    ENUM_ZERO       = 0
    ENUM_ONE        = 1
    ENUM_TWO        = 2
    ENUM_THREE      = 3
    ENUM_INVALID    = 4


#endclass.


print('Passes')
print('1) %d'%(EnumDemo['ENUM_TWO']))
print('2) %s'%(EnumDemo['ENUM_TWO']))
print('3) %s'%(EnumDemo.ENUM_TWO.name))
print('4) %d'%(EnumDemo.ENUM_TWO))
print()


print('Fails')
print('1) %d'%(EnumDemo.ENUM_TWOa))

The failure throws an exception as would be expected.

正如预期的那样,失败会引发异常。

A more robust version:

更强大的版本:

#!/usr/bin/env python3


class EnumDemo():


    enumeration =   (
                        'ENUM_ZERO',    # 0.
                        'ENUM_ONE',     # 1.
                        'ENUM_TWO',     # 2.
                        'ENUM_THREE',   # 3.
                        'ENUM_INVALID'  # 4.
                    )


    def name(self, val):
        try:

            name = self.enumeration[val]
        except IndexError:

            # Always return last tuple.
            name = self.enumeration[len(self.enumeration) - 1]

        return name


    def number(self, val):
        try:

            index = self.enumeration.index(val)
        except (TypeError, ValueError):

            # Always return last tuple.
            index = (len(self.enumeration) - 1)

        return index


#endclass.


print('Passes')
print('1) %d'%(EnumDemo().number('ENUM_TWO')))
print('2) %s'%(EnumDemo().number('ENUM_TWO')))
print('3) %s'%(EnumDemo().name(1)))
print('4) %s'%(EnumDemo().enumeration[1]))
print()
print('Fails')
print('1) %d'%(EnumDemo().number('ENUM_THREEa')))
print('2) %s'%(EnumDemo().number('ENUM_THREEa')))
print('3) %s'%(EnumDemo().name(11)))
print('4) %s'%(EnumDemo().enumeration[-1]))

When not used correctly this avoids creating an exception and, instead, passes back a fault indication. A more Pythonic way to do this would be to pass back "None" but my particular application uses the text directly.

如果使用不当,这将避免创建异常,而是传回故障指示。一种更 Pythonic 的方法是传回“无”,但我的特定应用程序直接使用文本。