python 高级语法与用法-枚举的简单用法

1、枚举

  • 可读性更强
from enum import Enum

class VIP(Enum):
    YELLOW = 1
    GREEN  = 2
    BALCK  = 3
    RED    = 4

print(VIP.BALCK)
print(type(VIP.BALCK))
# [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test17.py"
# VIP.BALCK
# <enum 'VIP'>

按照普通类来分析,类名.类变量 ,应该输出的是3,但是其实却是VIP.BALCK。

先不解释为什么。先说说,其实这种打印结果应该对调用该类的业务方来说,是更希望看到VIP.BALCK的吧,而不是一个数字3,也不知道这个意义是啥。

这就是说,枚举类不能按照普通类来分析。

接下来说说枚举类的特点和优势

  • 枚举类中的value不可变:Cannot reassign members;业务需求中,往往也需要定义的常量类型,是不允许被修改的。
  • from enum import Enum
    
    class VIP(Enum):
        YELLOW = 1
        GREEN  = 1
        BALCK  = 3
        RED    = 4
    
    print(VIP.GREEN)
    VIP.GREEN = 5
    # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test17.py"
    # VIP.GREEN
    # Traceback (most recent call last):
    #   File "/Users/anson/Documents/Project/python_ToolCodes/test17.py", line 10, in <module>
    #     VIP.GREEN = 5
    #   File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/enum/__init__.py", line 419, in __setattr__
    #     raise AttributeError('Cannot reassign members.')
    # AttributeError: Cannot reassign members.

    用普通类代替枚举类,被轻易修改
    class Common():
        GREEN = 1
    Common.GREEN = 3
    print(Common.GREEN)
    # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test17.py"
    # 3

    dict来替代枚举类,被轻易修改

    a = {"GREEN":1,"RED":4}
    a["GREEN"] = 3
    print(a)
    # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test17.py"
    # {'GREEN': 3, 'RED': 4}

     

  • 枚举类中不能存在相同的标签名
  • from enum import Enum
    
    class Animal(Enum):
        CAT = 1
        CAT = 2
    # anson@ansonwandeMacBook-Pro python_ToolCodes % python3 test19.py 
    # Traceback (most recent call last):
    #   File "test19.py", line 3, in <module>
    #     class Animal(Enum):
    #   File "test19.py", line 5, in Animal
    #     CAT = 2
    #   File "/usr/local/Cellar/python@3.8/3.8.3_2/Frameworks/Python.framework/Versions/3.8/lib/python3.8/enum.py", line 95, in __setitem__
    #     raise TypeError('Attempted to reuse key: %r' % key)
    # TypeError: Attempted to reuse key: 'CAT'

    需要注意的是,python2.7版本是允许有相同名称的标签的,但是目前所学的python3.8时不允许有相同名称的标签的

  • 获取枚举的标签和数值,该怎么操作VIP.YELLOW.name,VIP.YELLOW.value
  • from enum import Enum
    #coding=utf-8
    
    class VIP(Enum):
        YELLOW = 1
        GRAY   = 2
        BALCK  = 3
        RED    = 4
    print(VIP.YELLOW)
    print(VIP.YELLOW.name)
    print(VIP.YELLOW.value)
    # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test17.py"
    # VIP.YELLOW
    # YELLOW
    # 1

     

  • 枚举遍历
    from enum import Enum
    #coding=utf-8
    
    class VIP(Enum):
        YELLOW = 1
        GRAY   = 2
        BALCK  = 3
        RED    = 4
    for v in VIP:
        print(v)
    # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test17.py"
    # VIP.YELLOW
    # VIP.GRAY
    # VIP.BALCK
    # VIP.RED

     

  • 枚举比较
    • “==”比较:允许
      from enum import Enum
      #coding=utf-8
      
      class VIP(Enum):
          YELLOW = 1
          GRAY   = 2
          BALCK  = 3
          RED    = 4
      print(VIP.BALCK == VIP.GRAY)
      # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test17.py"
      # False
      
      

      >,<比较:不允许!!!

      from enum import Enum
      #coding=utf-8
      
      class VIP(Enum):
          YELLOW = 1
          GRAY   = 2
          BALCK  = 3
          RED    = 4
      print(VIP.BALCK > VIP.GRAY)
      # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test17.py"
      # Traceback (most recent call last):
      #   File "/Users/anson/Documents/Project/python_ToolCodes/test17.py", line 9, in <module>
      #     print(VIP.BALCK > VIP.GRAY)
      #   File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/enum/__init__.py", line 740, in __gt__
      #     raise TypeError("unorderable types: %s() > %s()" % (self.__class__.__name__, other.__class__.__name__))
      # TypeError: unorderable types: VIP() > VIP()

      is 比较:允许
      from enum import Enum
      #coding=utf-8
      
      class VIP(Enum):
          YELLOW = 1
          GRAY   = 2
          BALCK  = 3
          RED    = 4
      print(VIP.BALCK is VIP.BALCK)
      # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test17.py"
      # True
      枚举类之间比较:允许
      from enum import Enum
      #coding=utf-8
      
      class VIP1(Enum):
          YELLOW = 1
          GRAY   = 2
          BALCK  = 3
          RED    = 4
      
      class VIP2(Enum):
          YELLOW = 1
          GRAY   = 2
          BALCK  = 3
          RED    = 4
      print(VIP1.GRAY is VIP2.GRAY)
      # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test17.py"
      # False
       

 

  • 枚举类型转换
  • 值转为枚举标签
    from enum import Enum
    
    class Animal(Enum):
        CAT = 1
        DOG = 2
    
    a = 1
    print(Animal(a))
    # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test19.py"
    # Animal.CAT

     

  • 枚举小结
    1、IntEunm 与Enum 的区别是,IntEum 至于许标签值是Int的,float  
    
    from enum import IntEnum
    
    class Animal(IntEnum):
        CAT = 'sss'
        DOG = 2
    
    a = 1
    print(Animal(a))
    Traceback (most recent call last):
      File "test19.py", line 3, in <module>
        class Animal(IntEnum):
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/enum/__init__.py", line 230, in __new__
        enum_member = __new__(enum_class, *args)
    ValueError: invalid literal for int() with base 10: 'sss'
    2、枚举的标签是不允许重复的,但是枚举的值是可以重复的,然而开发时,往往是不需要重复的,这时候,我们可以用装饰器
    @unique来限制枚举的值不能重复
    from enum import Enum,unique
    @unique
    class Animal(Enum):
        CAT = 1
        DOG = 1
    
    a = 1
    print(Animal(a))
    
    # anson@ansonwandeMacBook-Pro python_ToolCodes % python3  test19.py
    # Traceback (most recent call last):
    #   File "test19.py", line 3, in <module>
    #     class Animal(Enum):
    #   File "/usr/local/Cellar/python@3.8/3.8.3_2/Frameworks/Python.framework/Versions/3.8/lib/python3.8/enum.py", line 860, in unique
    #     raise ValueError('duplicate values found in %r: %s' %
    # ValueError: duplicate values found in <enum 'Animal'>: DOG -> CAT

 

posted @ 2020-08-07 15:41  XiaoLee-C  阅读(566)  评论(0编辑  收藏  举报