枚举

枚举:枚举其实就是常量(不能被修改) 枚举类:用来定义枚举的类

定义枚举

定义枚举类,需要导入enum包里的Enum模块

  1. from enum import Enum

然后用class定义属性并赋值就行了,这些属性就是枚举

注意: 属性储存的是枚举名(如下:A储存的是”NameEnum.A”字符串) 枚举值储存在value属性下(如下,A.value储存的是 10 枚举值)

  1. from enum import Enum, unique
  2. class NameEnum(Enum):
  3. A = 10
  4. B = 20
  5. C = 30
  6. print(NameEnum.A)
  7. print(NameEnum.A.value)
  8. NameEnum.A.value = 40 # 如果尝试修改,会触发AttributeError异常
  1. NameEnum.A
  2. 10
  3. Traceback (most recent call last):
  4. File "D:\enum.py", line 361, in __setattr__
  5. raise AttributeError('Cannot reassign members.')
  6. AttributeError: Cannot reassign members

@unique装饰器

@unique修饰器可以帮助我们检查是否有重复的枚举值 需要导入enum包里的unique模块

  1. from enum import unique

如果有重复的枚举值,会抛出ValueError异常

  1. from enum import Enum, unique
  2. @unique
  3. class NameEnum(Enum):
  4. A = 10
  5. B = 20
  6. C = 20
  1. Traceback (most recent call last):
  2. File "D:\enum.py", line 834, in unique
  3. (enumeration, alias_details))
  4. ValueError: duplicate values found in <enum 'NameEnum'>: C -> B