在Python中,枚举是通过使用enum模块实现的。枚举有名称和值。可以使用名称或值来访问枚举。
要使用此模块,我们应该使用导入它。
import enum
枚举具有一些属性。这些是-
枚举可以显示为字符串或repr格式。
该type()方法可以显示枚举类型
有名称关键字,以显示枚举成员的名称。
枚举是可迭代的
import enum
class Rainbow(enum.Enum):
VIOLET = 1
INDIGO = 2
BLUE = 3
GREEN = 4
YELLOW = 5
ORANGE = 6
RED = 7
print('The 3rd Color of Rainbow is: ' + str(Rainbow(3)))
print('The number of orange color in rainbow is: ' + str(Rainbow['ORANGE'].value))
my_rainbow_green = Rainbow.GREEN
print('The selected color {} and Value {}'.format(my_rainbow_green.name, my_rainbow_green.value))输出结果
The 3rd Color of Rainbow is: Rainbow.BLUE The number of orange color in rainbow is: 6 The selected color GREEN and Value 4