How to convert int to Enum in python?

前端 未结 3 1848
独厮守ぢ
独厮守ぢ 2020-12-29 00:31

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?

3条回答
  •  感动是毒
    2020-12-29 01:25

    I think it is in simple words is to convert the int value into Enum by calling EnumType(int_value), after that access the name of the Enum object:

    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
    

提交回复
热议问题