python 枚举类型_Python 的枚举类型

起步

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

总结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值