美文网首页
Python枚举

Python枚举

作者: 人生苦短啊 | 来源:发表于2018-07-21 19:03 被阅读0次
    1. 枚举类型、枚举名称与枚举值

    枚举优点: 不可更改性, 不可重复性

    from enum import Enum
    
    class Vip(Enum):
        YELLOW = 1
        GREEN = 2
        RED = 3
    
    print(type(Vip.YELLOW.value))       # 枚举值            <class 'int'>
    print(type(Vip.YELLOW.name))        # 枚举名字          <class 'str'>
    print(type(Vip['RED']))            # 枚举类型          <enum 'Vip'>
    
    for v in Vip:
        print(v.name)       # 遍历枚举
    
    2. 枚举比较

    枚举只能进行等于比较不能进行大小比较

    from enum import Enum
    
    class Vip(Enum):
        YELLOW = 1
        GREEN = 1
        RED = 3
    
    class Vip2(Enum):
        YELLOW = 1
    
    result = Vip.YELLOW == Vip.GREEN        # True
    result = Vip.YELLOW is Vip.GREEN        # True
    result1 = Vip.YELLOW == 1               # False
    result1 = Vip.YELLOW == Vip2.YELLOW     # False
    print(result1)
    
    3. 枚举的别名
    from enum import Enum
    
    class Vip(Enum):
        YELLOW = 1
        YELLOW_CHILD = 1                # 两个枚举值相同, 第二个值系统会把它当做别名, 遍历的时候不会显示
        RED = 3
    
    for v in Vip:
        print(v)            # Vip.YELLOW
                            # Vip.RED
    
    for v in Vip.__members__:          # __members__会把别名也返回
        print(v)                        # YELLOW
                                        # YELLOW_CHILD
                                        # RED
    
    4. IntEnum,unique
    from enum import IntEnum,unique
    
    # InfEnum 会控制枚举里面都是int类型,如果不是就会报错,
    # unique 会控制枚举各个值是唯一的
    @unique
    class Vip(IntEnum):
        YELLOW = 1
        YELLOW_CHILD = 1          # 报错
        RED = 3
    
    print(Vip.YELLOW)
    

    相关文章

      网友评论

          本文标题:Python枚举

          本文链接:https://www.haomeiwen.com/subject/knecmftx.html