python- Enum 枚举
python Enum 枚举
概要
当一个变量有几种固定的取值时,通常我们喜欢将它定义为枚举类型,枚举类型用于声明一组命名的常数,使用枚举类型可以增强代买的可读性。
枚举是一组符号名称(枚举成员)的集合,枚举成员应该是唯一的、不可变的。在枚举中,可以对成员进行恒等比较,并且枚举本身是可迭代的
参考文件 http://www.coolpython.net/python_senior/data_type/enum.html
此模块定义了四个枚举类,它们可被用来定义名称和值的不重复集合: Enum, IntEnum, Flag 和 IntFlag。 此外还定义了一个装饰器 unique() 和一个辅助类 auto。
使用普通类直接实现枚举
每一个类变量就是一个枚举项,访问枚举项的方式为:类名加上类变量
class color():
YELLOW = 1
RED = 2
GREEN = 3
PINK = 4
# 访问枚举项
print(color.YELLOW) # 1
-
问题:安全性差
-
不应该存在
key相同的枚举项(类变量) -
不允许在类外直接修改枚举项的值
# 主要问题
class color():
YELLOW = 1
YELLOW = 3 # 注意这里又将YELLOW赋值为3,会覆盖前面的1
RED = 2
GREEN = 3
PINK = 4
# 访问枚举项
print(color.YELLOW) # 3
# 但是可以在外部修改定义的枚举项的值,这是不应该发生的
color.YELLOW = 99
print(color.YELLOW) # 99
枚举的定义
- 首先,定义枚举要导入
enum模块。 - 枚举定义用class关键字,继承
Enum类。
from enum import Enum
# 继承枚举类
class color(Enum):
YELLOW = 1
BEOWN = 1
# 注意BROWN的值和YELLOW的值相同,这是允许的,此时的BROWN相当于YELLOW的别名
RED = 2
GREEN = 3
PINK = 4
# 三种访问方式
print(color(1))
print(color["RED"])
print(color.RED)
print(color.BEOWN) # color.YELLOW 别名
print(color.YELLOW) # color.YELLOW
print(type(color.YELLOW)) # <enum 'color'>
print(color.YELLOW.value) # 1
print(type(color.YELLOW.value)) # <class 'int'>
print(color.YELLOW == 1) # False
print(color.YELLOW.value == 1) # True
print(color.YELLOW == color.YELLOW) # True
print(color.YELLOW == color2.YELLOW) # False
print(color.YELLOW is color2.YELLOW) # False
print(color.YELLOW is color.YELLOW) # True
注意事项如下:
1、枚举类不能用来实例化对象
2、访问枚举类中的某一项,直接使用类名访问加上要访问的项即可,比如 color.YELLOW
3、枚举类里面定义的Key = Value,在类外部不能修改Value值,也就是说下面这个做法是错误的
color.YELLOW = 2 # Wrong, can't reassign member
4、枚举项可以用来比较,使用 ==,或者 is
5、导入Enum之后,一个枚举类中的Key和Value,Key不能相同,Value可以相,但是Value相同的各项Key都会当做别名,
6、如果要枚举类中的Value只能是整型数字,那么,可以导入IntEnum,然后继承IntEnum即可,注意,此时,如果value为字符串的数字,也不会报错
枚举值唯一
from enum import unique
import enum
@unique
class ColorCode(enum.Enum):
RED = 1
BLUE = 1
BLACK = 3
# 因为有相同项,执行时会报错
枚举值遍历
import enum
from enum import unique
@unique
class ColorCode(enum.Enum):
RED = 1
BLUE = 2
BLACK = 3
for color in ColorCode:
print(color.name, color.value)
# 输出
RED 1
BLUE 2
BLACK 3

浙公网安备 33010602011771号