Enum可以把一组相关常量定义在一个class中,且class不可变,而且成员可以直接比较。
定义枚举类:
from enumimport Enum, unique
@uniqueclassWeekday(Enum):
Sun= 0# Sun的value被设定为0
Mon= 1Tue= 2Wed= 3Thu= 4Fri= 5Sat= 6
可以看到括号里面是Enum ,即继承自枚举类
然后给这个枚举类的每个成员赋予一个值
@unique装饰器可以帮助我们检查保证没有重复值。
使用:
>>> day1 = Weekday.Mon
>>> print(day1)
Weekday.Mon
>>> print(Weekday.Tue)
Weekday.Tue
>>> print(Weekday[‘Tue‘])
Weekday.Tue
>>> print(Weekday.Tue.value)
2
>>> print(day1 == Weekday.Mon)
True
>>> print(day1 == Weekday.Tue)
False
>>> print(Weekday(1))
Weekday.Mon
>>> print(day1 == Weekday(1))
True
>>> Weekday(7)
Traceback (most recent call last):
...
ValueError: 7 is not a valid Weekday
>>> for name, member in Weekday.__members__.items():
... print(name, ‘=>‘, member)
...
Sun => Weekday.Sun
Mon => Weekday.Mon
Tue => Weekday.Tue
Wed => Weekday.Wed
Thu => Weekday.Thu
Fri => Weekday.Fri
Sat => Weekday.Sat