Python 枚举类Enum

首先定义枚举类如下:

1
2
3
4
5
6
7
8
9
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. 常规用法

    1
    2
    3
    4
    5
    print(LibraryType.PERSONAL.name)
    # echo PERSONAL

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

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

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

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

参考资料:
enum-Support for enumerations