Enum学习
# #Enum 练习: from enum import Enum, unique #1、函数式API调用 # 第一个参数是枚举名称 # 第二个参数是枚举成员名称的源 Month = Enum('Month',('Jan','Feb','Mar')) for name,member in Month.__members__.items(): # list all enum members,including aliases,既然是map自然就会有items print(name,'=>',member,',',member.value) #value属性是自动赋给成员的int常量,默认从1开始记数 #2、自定义枚举类 @unique #装饰器可以帮助我们检查保证没有重复值。 ##如果错误,将返回: #line 834, in unique ## (enumeration, alias_details)) ##ValueError: duplicate values found in <enum 'Weekday'>: Tom -> Sun class Weekday(Enum): Sun = 0 # Sun的value被设定为0 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = 5 Sat = 6 Tom=0 #test a=Weekday print(a.Sun) print(a.Sun.value) print(a['Tue']) print(a['Tue'].value) print(a(0)) print(a(0).value) for key,value in a.__members__.items(): print(key,'-',value) ##Sun - Weekday.Sun ##Mon - Weekday.Mon ##Tue - Weekday.Tue ##Wed - Weekday.Wed ##Thu - Weekday.Thu ##Fri - Weekday.Fri ##Sat - Weekday.Sat print('-'*100) #作业: #把Student的gender属性改造为枚举类型,可以避免使用字符串: class Gender(Enum): Male = 0 Female = 1 class Student(object): def __init__(self, name, gender): self.name = name if isinstance(gender,Gender): self.gender = gender else: print('gender must be Gender type.') return 0 # 测试: bart = Student('Bart', Gender.Male) if bart.gender == Gender.Male: print('测试通过!') else: print('测试失败!')