enum

from enum import Enum
class Color(Enum):
    red=1
    green=2
    blue=3

print(Color.red)
#Color.red
print(repr(Color.red))
# <Color.red: 1>
print(type(Color.red))
# <enum 'Color'>
print(isinstance(Color.green, Color))
True

# 定义枚举时,成员名不允许重复
class Color(Enum):
    red = 1
    green = 2
    red = 3    # TypeError: Attempted to reuse key: 'red'

# 成员值允许相同,第二个成员的名称被视作第一个成员的别名
class Color(Enum):
    red   = 1
    green = 2
    blue  = 1
print(Color.red)              # Color.red
print(Color.blue)             # Color.red
print(Color.red is Color.blue)# True
print(Color(1))               # Color.red  在通过值获取枚举成员时,只能获取到第一个成员

# 若要不能定义相同的成员值,可以通过 unique 装饰
from enum import Enum, unique
@unique
class Color(Enum):
    red   = 1
    green = 2
    blue  = 1  # ValueError: duplicate values found in <enum 'Color'>: blue -> red

# 枚举取值
# 可以通过成员名来获取成员也可以通过成员值来获取成员:
print(Color['red'])  # Color.red  通过成员名来获取成员
print(Color(1))      # Color.red  通过成员值来获取成员

# 每个成员都有名称属性和值属性:
member = Color.red
print(member.name)   # red
print(member.value)  # 1
# 支持迭代的方式遍历成员,按定义的顺序,如果有值重复的成员,只获取重复的第一个成员:
for color in Color:
    print(color)
# 特殊属性 __members__ 是一个将名称映射到成员的有序字典(其实就是列表套元组,元组:(成员名,成员)),也可以通过它来完成遍历:
print(Color.__members__)  #OrderedDict([('red', <Color.red: 1>), ('green', <Color.green: 2>), ('blue', <Color.blue: 3>)])
for color in Color.__members__.items():
    print(color)          # ('red', <Color.red: 1>)
    print(color[0])       #red
    print(color[1])       #Color.red


# 枚举比较
# 枚举的成员可以通过 is 同一性比较或通过 == 等值比较:
print(Color.red is Color.red)             #True
print(Color.red is not Color.blue)        #True
print(Color.blue == Color.red)            #False
print(Color.blue != Color.red)            #True

# 枚举成员不能进行大小比较:
print(Color.red < Color.blue)               ## TypeError: unorderable types: Color() < Color()

# 扩展枚举 IntEnum
# IntEnum 是 Enum 的扩展,不同类型的整数枚举也可以相互比较:
from enum import IntEnum
class Shape(IntEnum):
    circle = 1
    square = 2

class Request(IntEnum):
    post = 1
    get = 2

print(Shape.circle == 1)            # True
print(Shape.circle < 3)             # True
print(Shape.circle == Request.post) # True
print(Shape.circle >= Request.post) # True
原文地址:https://www.cnblogs.com/Hale-wang/p/11758466.html