Python基础-23枚举
23 枚举
枚举是一组符号名称(枚举成员)的集合,枚举成员应该是唯一的、不可变的。
23.1 使用普通类实现枚举类
class basicWeek():
SUN=0
MON=1
TUE=2
WED=3
THU=4
FRI=5
SAT=6
# 获取值
print(basicWeek.SUN) # 0
虽然这样也可以实现,但不严谨,也不安全,原因如下所示:
- 枚举类中,不允许存在相同的枚举项(类变量)
- 不允许在类外面直接修改枚举项的值
class basicWeek():
SUN=0
MON=1
TUE=2
WED=3
THU=4
FRI=5
SAT=6
SUN=7 # 这里会覆盖前面已经定义的值
# 获取值
print(basicWeek.SUN) # 7
# 在外面修改值
basicWeek.SUN=99
# 再次获取的值为修改后的值
print(basicWeek.SUN) # 99
为了解决这种问题,我们引入枚举类
23.2 枚举类
在Python中使用枚举类,可以引入内置模块Enum,如下所示:
from enum import Enum
class EnumWeek(Enum):
SUN = 0
MON=1
TUE=2
WED=3
THU=4
FRI=5
SAT=6
print(EnumWeek.SUN) # EnumWeek.SUN
print(type(EnumWeek.SUN)) # <enum "EnumWeek">
print(EnumWeek.SUN.value) # 0
print(EnumWeek(5)) # EnumWeek.FRI
print(type(EnumWeek.SUN.value)) # <class "int">
print(EnumWeek.SUN.value == 0) # True
print(EnumWeek.SUN == EnumWeek2.SUN) # False
print(EnumWeek.SUN == EnumWeek.SUN) # True
print(EnumWeek.SUN is EnumWeek2.SUN) # False
print(EnumWeek.SUN is EnumWeek.SUN) # True
使用枚举类注意事项如下所示:
- 枚举类不能用来实例化对象
- 访问枚举类中的项,直接使用类名.访问项,如EnumWeek.SUN
- 枚举类中定义的key=value,在类外部不允许修改
- 枚举类可以用来==、is来进行比较
- 枚举类允许有多个名称作为某个相同值的别名
from enum import Enum
class EnumWeek(Enum):
SUN = 0
MON=1
TUE=2
WED=3
THU=4
FRI=5
SAT=0
print(EnumWeek.SAT) # EnumWeek.SUN
- 如果不允许枚举类出现相同值的时,可以使用装饰器@unique
from enum import Enum,unique
@unique
class EnumWeek(Enum):
SUN = 0
MON=1
TUE=2
WED=3
THU=4
FRI=5
SAT=0
输出结果如下所示:
Traceback (most recent call last):
File "C:UsersadminDocumentsPyCharmProjectsMyPythonProjectsLearningCodeLearningEnum.py", line 4, in <module>
class EnumWeek(Enum):
File "D:Program FilesPythonlibenum.py", line 1013, in unique
raise ValueError("duplicate values found in %r: %s" %
ValueError: duplicate values found in <enum "EnumWeek">: SAT -> SUN
- 使用自动设定的值
from enum import Enum,unique,auto
@unique
class EnumWeek(Enum):
SUN = auto()
MON=auto()
TUE=auto()
WED=auto()
THU=auto()
FRI=auto()
SAT=auto()
print(EnumWeek.SAT.value) # 7
print(EnumWeek.WED.value) # 4
- 枚举类是允许迭代的
from enum import Enum,unique,auto
@unique
class EnumWeek(Enum):
SUN = auto()
MON=auto()
TUE=auto()
WED=auto()
THU=auto()
FRI=auto()
SAT=auto()
for week in EnumWeek:
print(f"week is {week}:{week.value}")
输出结果如下所示:
week is EnumWeek.SUN:1
week is EnumWeek.MON:2
week is EnumWeek.TUE:3
week is EnumWeek.WED:4
week is EnumWeek.THU:5
week is EnumWeek.FRI:6
week is EnumWeek.SAT:7
原文地址:https://www.jianshu.com/p/391c9717525d
本文同步在微信订阅号上发布,如各位小伙伴们喜欢我的文章,也可以关注我的微信订阅号:woaitest,或扫描下面的二维码添加关注: