Python 枚举类Enum

首先定义枚举类如下:

from enum import Enum

class LibraryType(Enum):
    PERSONAL = 100
    PUBLIC = 200

    @classmethod
    def has_value(cls, value):
        return any(value == item.value for item in cls)
  1. 常规用法

    print(LibraryType.PERSONAL.name)
    # echo PERSONAL
    
    print(LibraryType.PERSONAL.value)
    # echo 100
    
  2. 判断值是否存在

    print(LibraryType.has_value(100))
    # echo True
    
  3. 通过值获取属性名称

    print(LibraryType(100).name)
    # echo PERSONAL
    
  4. 通过属性名称获取值

    print(LibraryType['PUBLIC'].value)
    # echo 200
    

参考资料:
enum-Support for enumerations