Python枚举转换

先看一个枚举类

from enum import Enum
class Color(Enum):
    YELLOW = 1
    GREEN = 2
    BLACK = 3
    RED = 4

如何把a=1转换成枚举类型,很简单,直接使用方法Color(a)就可以

from enum import Enum

class Color(Enum):
    YELLOW = 1
    GREEN = 2
    BLACK = 3
    RED = 4

a = 1
print(Color(a))
----------------------------------
输出:
Color.YELLOW

使用具体的值来访问枚举类型是一种方案,可以看做一个类型转换,但不是一个真正的类型转换。

注意:如果这个枚举类中不存在这个值是会报错的:

from enum import Enum

class Color(Enum):
    YELLOW = 1
    GREEN = 2
    BLACK = 3
    RED = 4

a = 6
print(Color(a))
----------------------
Traceback (most recent call last):
  File "E:/projects/python_learn/eleven/c7.py", line 16, in 
    print(Color(a))
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\enum.py", line 291, in __call__
    return cls.__new__(cls, value)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\enum.py", line 533, in __new__
    return cls._missing_(value)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\enum.py", line 546, in _missing_
    raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 6 is not a valid Color

你可能感兴趣的:(Python)