如何在Python中将int转换为Enum? [英] How to convert int to Enum in python?

查看:379
本文介绍了如何在Python中将int转换为Enum?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用新的枚举功能(通过 backport enum34 )与python 2.7.6。



给定以下定义,如何将int转换为相应的枚举值?

 从枚举导入枚举

class水果(枚举):
Apple = 4
橙色= 5
梨= 6

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



我的用例是我有一个记录的csv文件,记录到一个对象中。其中一个文件字段是表示枚举的整数字段。当我填充对象时,我想将该整数字段从文件转换为对象中相应的枚举值。

解决方案

'调用'code>枚举类:

 水果(5 )

5 转换为 Fruit.Orange

 >>>从枚举导入枚举
>>>>水果(枚举):
... Apple = 4
...橙色= 5
...梨= 6
...
>> ;>水果(5)
< Fruit.Orange:5>

程序化访问枚举成员及其属性文档部分:



$ block code code code code code code code code code code code code code < b $ b准确的颜色在程序写入时不知道)。 枚举允许这样的
访问:

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



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

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

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.

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.

解决方案

'Call' the Enum class:

Fruit(5)

to turn 5 into Fruit.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 attributes section of the documentation:

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

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

这篇关于如何在Python中将int转换为Enum?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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