枚举
枚举:枚举其实就是常量(不能被修改) 枚举类:用来定义枚举的类
定义枚举
定义枚举类,需要导入enum包里的Enum模块
from enum import Enum
然后用class定义属性并赋值就行了,这些属性就是枚举
注意: 属性储存的是枚举名(如下:A储存的是”NameEnum.A”字符串) 枚举值储存在value属性下(如下,A.value储存的是 10 枚举值)
from enum import Enum, unique
class NameEnum(Enum):
A = 10
B = 20
C = 30
print(NameEnum.A)
print(NameEnum.A.value)
NameEnum.A.value = 40 # 如果尝试修改,会触发AttributeError异常
NameEnum.A
10
Traceback (most recent call last):
File "D:\enum.py", line 361, in __setattr__
raise AttributeError('Cannot reassign members.')
AttributeError: Cannot reassign members
@unique装饰器
@unique修饰器可以帮助我们检查是否有重复的枚举值 需要导入enum包里的unique模块
from enum import unique
如果有重复的枚举值,会抛出ValueError异常
from enum import Enum, unique
@unique
class NameEnum(Enum):
A = 10
B = 20
C = 20
Traceback (most recent call last):
File "D:\enum.py", line 834, in unique
(enumeration, alias_details))
ValueError: duplicate values found in <enum 'NameEnum'>: C -> B