点击此处浏览总目录

枚举类

当需要定义常量时,一个办法是用大写变量通过整数来定义
好处是简单,缺点是类型是int,并且仍然是变量
Enum可以把一组相关常量定义在一个class中,且class不可变,而且成员可以直接比较,这样这些相关常量就不会变化了

 

  使用枚举类

    from enum import Enum
    Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
    
    for name, member in Month.__members__.items():
        print(name, '=>', member, ',', member.value)   #value属性则是自动赋给成员的int常量,默认从1开始计数
        
    #输出:Jan => Month.Jan , 1
    #输出:Feb => Month.Feb , 2
    #输出:Mar => Month.Mar , 3
    #输出:Apr => Month.Apr , 4
    #输出:May => Month.May , 5
    #输出:Jun => Month.Jun , 6
    #输出:Jul => Month.Jul , 7
    #输出:Aug => Month.Aug , 8
    #输出:Sep => Month.Sep , 9
    #输出:Oct => Month.Oct , 10
    #输出:Nov => Month.Nov , 11
    #输出:Dec => Month.Dec , 12

 

  自定义枚举类

  如果需要更精确地控制枚举类型,可以从Enum派生出自定义类

    from enum import Enum, unique
    
    @unique    #@unique装饰器可以帮助我们检查保证没有重复值
    class Weekday(Enum):
        Sun = 00
        Mon = 01
        Tue = 02
        Wed = 03
        Thu = 04
        Fri = 05
        Sat = 06
        
    day1 = Weekday.Mon
    print(day1)    #输出:Weekday.Mon
    print(day1.value)    #输出:01,value属性是枚举常量的值
    
    print(Weekday.Tue)  #输出:Weekday.Tue
    print(Weekday['Tue'])  #输出:Weekday.Tue,可用成员名称引用枚举常量
    print(Weekday['Tue'].value)  #输出:02
    
    print(day1 == Weekday.Mon)  #输出:True
    print(day1 == Weekday.Tue)  #输出:False
    
    print(Weekday('03'))    #输出:Weekday.Wed,根据value值获取枚举常量
    print(Weekday('03').value)    #输出:03,根据value值获取枚举常量
    
    print(day1 == Weekday('01'))   #输出:True
    Weekday(7)    #报错
    
    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

 

posted @ 2019-06-06 13:47  立业的博客  阅读(260)  评论(0编辑  收藏  举报