起步
Color = {
'RED' : 1,
'GREEN': 2,
'BLUE' : 3,
}
class Color:
RED = 1
GREEN = 2
BLUE = 3
使用 Enum
from enum import Enum
class Color(Enum):
red = 1
green = 2
blue = 3
>>> print(Color.red)
Color.red
>>> print(repr(Color.red))
>>> type(Color.red)
>>> 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 在通过值获取枚举成员时,只能获取到第一个成员
from enum import Enum, unique
@unique
class Color(Enum):
red = 1
green = 2
blue = 1 # ValueError: duplicate values found in : 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)
for color in Color.__members__.items():
print(color) # ('red', )
枚举比较
Color.red is Color.red
Color.red is not Color.blue
Color.blue == Color.red
Color.blue != Color.red
Color.red < Color.blue # TypeError: unorderable types: Color() < Color()
扩展枚举 IntEnum
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
总结