在开发项目的时候,我们经常要定义常量,在python中我们如何定义常量?答案:同样是枚举 Enum类
在python中如何定义枚举类型,例如星期
from enum import Enum, unique
@unique #装饰器可以帮助我们检查保证没有重复值
class Weekday(Enum):
Mon = 0
Tue = 1
Wed = 2
Thu = 3
Fir = 4
Sat = 5
Sun = 6
Weekday.Mon = 3 #errro 不能对枚举类型赋值
day = Weekday.Mon
print(day) # Weekday.Mon
print(day.value) # 0
for name, member in Weekday.members.items():
print(name, member)
#
Mon Weekday.Mon
Tue Weekday.Tue
Wed Weekday.Wed
Thu Weekday.Thu
Fir Weekday.Fir
Sat Weekday.Sat
Sun Weekday.Sun
网友评论