from enum import Enum, unique
Month = Enum('Month',('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'))
#遍历枚举类
for a in Month:
print(a.name, ' = ', a.value) # value属性是自动赋给成员的int常量,默认从1开始计数
day1 = Month.Jan
print(day1.name, ' = ', day1.value)
print('day1 == Month.Jan : ', day1 == Month.Jan)
print('day1 == Month.Feb : ', day1 == Month.Feb)
print('day1 in Month : ', day1 in Month)
@unique #装饰器可以帮助我们检查是否有重复值
class Weekday(Enum):
Sun,Mon,Tue,Wed,Thu,Fri,Sat = 0, 1, 2, 3, 4, 5, 6 # 也可以一个地赋值
day2 = Weekday.Sun
print('day2.name = ', day2.name)
print('day2.value = ', day2.value)
print('day2 == Weekday.Sun : ', day2 == Weekday['Sun'] ) #以字典的方式访问枚举类的值
print('day2 == Weekday.Sun : ', day2 == Weekday(0) ) #用数字获取相应的枚举类的值
print('day2 == Weekday.Wed : ', day2 == Weekday.Wed) #以 dot 号访问枚举类的值
print('day2 in Weekday :', day2 in Weekday)
# 下面故意在枚举类中使用重复的值, 看看会报什么错误信息
try:
@unique
class Sex(Enum):
Boy = 0
Girl = 1
Unknown = 0
except Exception as e:
print(e)
#从报错信息中可以看到, 枚举值 Unknown 与 Boy 重复