用枚举来表示
1 绿
2 黄
3 红
4 黑
需要引入Enum
模块
所有的枚举类型都是
Enum
的子类
比写1,2,3,4,5可读性是强很多的。枚举的标识名字最好用大写来表示
from enum import Enum
class Color(Enum):
YELLOW = 1
GREEN = 2
BLACK = 3
RED = 4
print(Color.YELLOW)
--------------------------------------
输出:
Color.YELLOW
打印Color.YELLOW
的意义重在它的标识,而不是它的值。并且标识是不能有相同的,把GREEN
换成YELLOW
,如下所示:
from enum import Enum
class Color(Enum):
YELLOW = 1
YELLOW = 2
BLACK = 3
RED = 4
print(Color.YELLOW)
--------------------------
输出:
Traceback (most recent call last):
File "E:/projects/python_learn/eleven/c1.py", line 12, in <module>
class Color(Enum):
File "E:/projects/python_learn/eleven/c1.py", line 14, in Color
YELLOW = 2
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\enum.py", line 92, in __setitem__
raise TypeError('Attempted to reuse key: %r' % key)
TypeError: Attempted to reuse key: 'YELLOW'
这样是有报错的,所以标识是不能有相同的。