python枚举法方法很多,下面列举几种常见实现方式:
1、方法1
class SeriesEnum:
one, two, three, four, five, six, seven, eight, nine, ten = range(10)
print(SeriesEnum.eight) # 7
2 方法2
class SeriesEnum():
one = 1
two = 2
three = 3
four = 4
print(SeriesEnum.one) # 1
1、Enum 默认键值value可重复,,键Key不能重复
from enum import Enum
class SeriesEnum(Enum):
one = 1
two = 2
three = 3
four = 4
print(SeriesEnum.one) # SeriesEnum.one
print(SeriesEnum.one.value) # 1
print(SeriesEnum['two']) # SeriesEnum.two
print(SeriesEnum['two'].value) # 2
print(SeriesEnum(2)) # SeriesEnum.two
2、如果要求键不能重复,可以使用 unique
from enum import Enum, unique
@unique
class SeriesEnum(Enum):
one = 1
two = 2
three = 3
four = 4
print(SeriesEnum.one) # SeriesEnum.one
print(SeriesEnum.one.value) # 1
3、第一个参数是枚举类的类名;第二个参数是一个元组
import enum
# 定义Number枚举类
Number = enum.Enum('Number', ('one', 'two', 'three', 'four'))
print(Number.One) # Number.one
print(Number.one.value) # 1