枚举是一组符号名称(枚举成员)的集合,枚举成员应该是唯一的、不可变的。
成都创新互联公司是一家专业提供南岸企业网站建设,专注与网站设计、网站建设、HTML5、小程序制作等业务。10年已为南岸众多企业、政府机构等服务。创新互联专业网络公司优惠进行中。
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
为了解决这种问题,我们引入枚举类
在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)) #
print(EnumWeek.SUN.value) # 0
print(EnumWeek(5)) # EnumWeek.FRI
print(type(EnumWeek.SUN.value)) #
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
使用枚举类注意事项如下所示:
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
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:\Users\admin\Documents\PyCharmProjects\MyPythonProjects\LearningCode\LearningEnum.py", line 4, in
class EnumWeek(Enum):
File "D:\Program Files\Python\lib\enum.py", line 1013, in unique
raise ValueError('duplicate values found in %r: %s' %
ValueError: duplicate values found in : 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/391cd
本文同步在微信订阅号上发布,如各位小伙伴们喜欢我的文章,也可以关注我的微信订阅号:woaitest,或扫描下面的二维码添加关注: