一文带你了解Python枚举类enum的使用

作者:XerCis 时间:2022-05-27 07:46:51 

简介

枚举是与多个唯一常量绑定的一组符号

因为枚举表示的是常量,建议枚举成员名用大写

IntEnum 便于进行系统交互

初试

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
print(Color.RED.name)  # RED

遍历

from enum import Enum

class Shake(Enum):
   VANILLA = 7
   CHOCOLATE = 4
   COOKIES = 9
   MINT = 3

for shake in Shake:
   print(shake)
# Shake.VANILLA
# Shake.CHOCOLATE
# Shake.COOKIES
# Shake.MINT

__members__ 列出 name 和成员

from enum import Enum

class Shape(Enum):
   SQUARE = 2
   DIAMOND = 1
   CIRCLE = 3
   ALIAS_FOR_SQUARE = 2

for name, member in Shape.__members__.items():
   print(name, member)
# SQUARE Shape.SQUARE
# DIAMOND Shape.DIAMOND
# CIRCLE Shape.CIRCLE
# ALIAS_FOR_SQUARE Shape.SQUARE

可哈希

枚举成员可哈希,可用于字典和集合

from enum import Enum

class Color(Enum):
   RED = 1
   GREEN = 2
   BLUE = 3

apples = {}
apples[Color.RED] = 'red delicious'
apples[Color.GREEN] = 'granny smith'
print(apples)
# {<Color.RED: 1>: 'red delicious', <Color.GREEN: 2>: 'granny smith'}

访问成员

  • name:变量名

  • value:值

from enum import Enum

class Color(Enum):
   RED = 1
   GREEN = 2
   BLUE = 3

# 通过值访问
print(Color(1))  # Color.RED
print(Color(3))  # Color.BLUE

# 通过name访问
print(Color['RED'])  # Color.RED
print(Color['GREEN'])  # Color.GREEN

# 访问成员的name或value
print(Color.RED.name)  # RED
print(Color.RED.value)  # 1

唯一枚举值

装饰器 @unique

from enum import Enum, unique

@unique
class Mistake(Enum):
   ONE = 1
   TWO = 2
   THREE = 3
   FOUR = 3
# ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE

自动枚举值

如果枚举值不重要,可以用 auto(), 默认从 1 开始

from enum import Enum, auto

class Color(Enum):
   RED = auto()
   BLUE = auto()
   GREEN = auto()

print(Color(1))  # Color.RED
print(list(Color))  # [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

比较运算

  • Enum 不支持直接排序

  • IntEnum 可直接排序

Enum

from enum import Enum

class Color(Enum):
   RED = 1
   BLUE = 2
   GREEN = 3

print(Color.RED is Color.RED)  # True
print(Color.RED is Color.BLUE)  # False
print(Color.RED is not Color.BLUE)  # True

try:
   Color.RED < Color.BLUE  # Enum不支持直接排序
except Exception as e:
   print(e)  # '<' not supported between instances of 'Color' and 'Color'

print(Color.BLUE == Color.RED)  # Fasle
print(Color.BLUE != Color.RED)  # True
print(Color.BLUE == Color.BLUE)  # True

print(Color.BLUE == 2)  # False

IntEnum

from enum import IntEnum

class Color(IntEnum):
   RED = 1
   BLUE = 2
   GREEN = 3

# IntEnum可直接排序
print(Color.RED < Color.BLUE)  # True

print(Color.BLUE == 2)  # True

功能性API

官方教程

from enum import Enum

class Animal(Enum):
   ANT = 1
   BEE = 2
   CAT = 3
   DOG = 4

Animal = Enum('Animal', 'ANT BEE CAT DOG')  # 同上

print(Animal)  # <enum 'Animal'>
print(Animal.ANT)  # <Animal.ANT: 1>
print(Animal.ANT.value)  # 1
print(list(Animal))  # [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]

IntEnum

官方教程

除了不可以直接和 Enum 比较,其他都类似整数

from enum import Enum, IntEnum

class Color(Enum):
   RED = 1
   GREEN = 2

class Shape(IntEnum):
   CIRCLE = 1
   SQUARE = 2

class Request(IntEnum):
   POST = 1
   GET = 2

print(Shape.CIRCLE == Color.RED)  # False

print(Shape == 1)  # False
print(Shape.CIRCLE == 1)  # True
print(Shape.CIRCLE == Request.POST)  # True

print(int(Shape.CIRCLE))  # 1
print(['a', 'b', 'c'][Shape.CIRCLE])  # b
print([i for i in range(Shape.SQUARE)])  # [0, 1]

IntFlag

官方教程

类似 int,IntFlag 成员使用按位运算符得到的结果仍然是 IntFlag 成员

IntFlag 和 Enum 的一个区别在于,如果没有设置任何标志(值为 0),则其布尔值为 False

from enum import IntFlag

class Perm(IntFlag):
   R = 4  # 读
   W = 2  # 写
   X = 1  # 执行

print(Perm.R | Perm.W)  # <Perm.R|W: 6>
print(Perm.R + Perm.W)  # 6

RW = Perm.R | Perm.W
print(Perm.R in RW)  # True
from enum import IntFlag

class Perm(IntFlag):
   R = 4  # 读
   W = 2  # 写
   X = 1  # 执行
   RWX = 7  # 读写执行

print(Perm.RWX)  # <Perm.RWX: 7>
print(~Perm.RWX)  # <Perm.-8: -8>

print(Perm.R & Perm.X)  # <Perm.0: 0>
print(bool(Perm.R & Perm.X))  # False

print(Perm.X | 8)  # <Perm.8|X: 9>

Flag

官方教程

  • Flag 与 IntFlag 类似,成员可使用按位运算符进行组合,但不可与其他 Flag 或 int 组合

  • 推荐用 auto() 作为值

from enum import Flag, auto

class Color(Flag):
   BLACK = 0
   RED = auto()
   BLUE = auto()
   GREEN = auto()
   WHITE = RED | BLUE | GREEN

print(Color.RED & Color.GREEN)  # <Color.0: 0>
print(bool(Color.RED & Color.GREEN))  # False
print(Color.WHITE)  # <Color.WHITE: 7>

print(Color.BLACK)  # <Color.BLACK: 0>
print(bool(Color.BLACK))  # False

知识点

不支持同名

来源:https://blog.csdn.net/lly1122334/article/details/127528887

标签:Python,枚举类,enum
0
投稿

猜你喜欢

  • 最小asp后门程序

    2011-04-03 10:35:00
  • python logging模块的分文件存放详析

    2023-04-02 20:27:32
  • 微信支付的开发流程详解

    2023-09-07 08:54:45
  • pytorch fine-tune 预训练的模型操作

    2023-05-02 01:05:25
  • python爬取招聘要求等信息实例

    2021-01-27 21:22:36
  • pydantic-resolve嵌套数据结构生成LoaderDepend管理contextvars

    2023-01-12 22:21:05
  • 用CSS实现柱状图(Bar Graph)的方法(一)—基于列表元素的柱状图

    2008-05-26 13:03:00
  • Pycharm使用远程linux服务器conda/python环境在本地运行的方法(图解))

    2021-05-13 07:42:11
  • python 字符串只保留汉字的方法

    2022-07-15 00:34:49
  • Python 异步等待任务集合

    2022-08-14 17:23:22
  • python 删除字符串中连续多个空格并保留一个的方法

    2021-08-16 14:07:25
  • 《Python学习手册》学习总结

    2021-09-17 08:55:01
  • Python3中对range()逆序的解释

    2023-03-26 10:27:59
  • 一实用的table内容排序Javascript类库

    2008-11-02 15:03:00
  • swfobject2.1居中问题

    2008-12-15 17:18:00
  • asp.net中不能在DropDownList中选择多个项 原因分析及解决方法

    2023-07-23 22:15:27
  • python实现根据给定坐标点生成多边形mask的例子

    2022-03-22 14:40:15
  • 编程活动中几个不良现象

    2008-09-01 12:23:00
  • Html的几个小技巧

    2011-04-29 14:02:00
  • Python入门篇之正则表达式

    2021-10-20 09:01:34
  • asp之家 网络编程 m.aspxhome.com