简单 Python 快乐之旅之:Python 基础语法之枚举的使用例子
Python 中定义枚举需要导入 enum 模块,使用 class 来继承 Enum 类。基本语法如下:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
枚举的成员名称不允许重复,成员值允许重复但尽量不要重复。示例代码:
# Python Create Enum
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
# To access the values of an Enum Class
print(Color.GREEN.name)
print(Color.GREEN.value)
if (Color.GREEN.value == Color.BLUE.value):
print(Color.GREEN, 'equals', Color.BLUE)
else:
print(Color.GREEN, 'not equals', Color.BLUE)
# To get more information about the Enum member
print(repr(Color.GREEN))
执行和输出:
参考资料
Python Create Enum