python 系列(枚举类型)(python枚举类型enum用法)
off999 2024-09-18 22:40 17 浏览 0 评论
枚举 - 枚举类型
该enum模块定义了具有迭代和比较功能的枚举类型。它可用于为值创建定义明确的符号,而不是使用文字整数或字符串。
创建枚举
class通过子类化Enum和添加描述值的类属性,使用语法 定义新的枚举。
enum_create.py
import enum class BugStatus(enum.Enum): new = 7 incomplete = 6 invalid = 5 wont_fix = 4 in_progress = 3 fix_committed = 2 fix_released = 1 print('\nMember name: {}'.format(BugStatus.wont_fix.name)) print('Member value: {}'.format(BugStatus.wont_fix.value))
在Enum解析类时,将成员转换为实例。每个实例都具有name与成员名称value对应的属性以及与在类定义中分配给名称的值对应的属性。
$ python3 enum_create.py Member name: wont_fix Member value: 4
迭代
迭代枚举类会产生枚举的各个成员。
enum_iterate.py
import enum class BugStatus(enum.Enum): new = 7 incomplete = 6 invalid = 5 wont_fix = 4 in_progress = 3 fix_committed = 2 fix_released = 1 for status in BugStatus: print('{:15} = {}'.format(status.name, status.value))
成员按照在类定义中声明的顺序生成。名称和值不用于以任何方式对它们进行排序。
$ python3 enum_iterate.py new = 7 incomplete = 6 invalid = 5 wont_fix = 4 in_progress = 3 fix_committed = 2 fix_released = 1
比较枚举
由于枚举成员未被排序,因此它们仅支持通过标识和相等性进行比较。
enum_comparison.py
import enum class BugStatus(enum.Enum): new = 7 incomplete = 6 invalid = 5 wont_fix = 4 in_progress = 3 fix_committed = 2 fix_released = 1 actual_state = BugStatus.wont_fix desired_state = BugStatus.fix_released print('Equality:', actual_state == desired_state, actual_state == BugStatus.wont_fix) print('Identity:', actual_state is desired_state, actual_state is BugStatus.wont_fix) print('Ordered by value:') try: print('\n'.join(' ' + s.name for s in sorted(BugStatus))) except TypeError as err: print(' Cannot sort: {}'.format(err))
大于和小于比较运算符引发 TypeError异常。
$ python3 enum_comparison.py Equality: False True Identity: False True Ordered by value: Cannot sort: '<' not supported between instances of 'BugStatus ' and 'BugStatus'
将IntEnum类用于枚举,其中成员需要表现得更像数字 - 例如,以支持比较。
enum_intenum.py
import enum class BugStatus(enum.IntEnum): new = 7 incomplete = 6 invalid = 5 wont_fix = 4 in_progress = 3 fix_committed = 2 fix_released = 1 print('Ordered by value:') print('\n'.join(' ' + s.name for s in sorted(BugStatus))) $ python3 enum_intenum.py Ordered by value: fix_released fix_committed in_progress wont_fix invalid incomplete new
唯一枚举值
具有相同值的枚举成员将作为对同一成员对象的别名引用进行跟踪。别名不会导致重复值存在于迭代器中Enum。
enum_aliases.py
import enum class BugStatus(enum.Enum): new = 7 incomplete = 6 invalid = 5 wont_fix = 4 in_progress = 3 fix_committed = 2 fix_released = 1 by_design = 4 closed = 1 for status in BugStatus: print('{:15} = {}'.format(status.name, status.value)) print('\nSame: by_design is wont_fix: ', BugStatus.by_design is BugStatus.wont_fix) print('Same: closed is fix_released: ', BugStatus.closed is BugStatus.fix_released)
因为by_design并且closed是其他成员的别名,所以当迭代时,它们不会在输出中单独出现 Enum。成员的规范名称是附加到值的第一个名称。
$ python3 enum_aliases.py new = 7 incomplete = 6 invalid = 5 wont_fix = 4 in_progress = 3 fix_committed = 2 fix_released = 1 Same: by_design is wont_fix: True Same: closed is fix_released: True
要要求所有成员都具有唯一值,请将@unique 装饰器添加到Enum。
enum_unique_enforce.py
import enum @enum.unique class BugStatus(enum.Enum): new = 7 incomplete = 6 invalid = 5 wont_fix = 4 in_progress = 3 fix_committed = 2 fix_released = 1 # This will trigger an error with unique applied. by_design = 4 closed = 1
具有重复值的成员在解释类ValueError时会触发异常Enum。
$ python3 enum_unique_enforce.py Traceback (most recent call last): File "enum_unique_enforce.py", line 11, in <module> class BugStatus(enum.Enum): File ".../lib/python3.6/enum.py", line 834, in unique (enumeration, alias_details)) ValueError: duplicate values found in <enum 'BugStatus'>: by_design -> wont_fix, closed -> fix_released
以编程方式创建枚举
在某些情况下,以编程方式创建枚举更方便,而不是在类定义中对它们进行硬编码。对于这些情况,Enum还支持将成员名称和值传递给类构造函数。
enum_programmatic_create.py
import enum BugStatus = enum.Enum( value='BugStatus', names=('fix_released fix_committed in_progress ' 'wont_fix invalid incomplete new'), ) print('Member: {}'.format(BugStatus.new)) print('\nAll members:') for status in BugStatus: print('{:15} = {}'.format(status.name, status.value))
该value参数是枚举,其被用于建立成员的表示的名称。该names参数列表枚举的成员。当传递单个字符串时,它将在空格和逗号上拆分,并且生成的标记将用作成员的名称,这些成员将自动分配以值开头的值1。
$ python3 enum_programmatic_create.py Member: BugStatus.new All members: fix_released = 1 fix_committed = 2 in_progress = 3 wont_fix = 4 invalid = 5 incomplete = 6 new = 7
为了更好地控制与成员关联的值, names可以使用两部分元组序列或将名称映射到值的字典替换字符串。
enum_programmatic_mapping.py
import enum BugStatus = enum.Enum( value='BugStatus', names=[ ('new', 7), ('incomplete', 6), ('invalid', 5), ('wont_fix', 4), ('in_progress', 3), ('fix_committed', 2), ('fix_released', 1), ], ) print('All members:') for status in BugStatus: print('{:15} = {}'.format(status.name, status.value))
在此示例中,给出了由两部分组成的元组的列表,而不是仅包含成员名称的单个字符串。这使得可以BugStatus使用与定义的版本相同的顺序重建枚举的枚举enum_create.py。
$ python3 enum_programmatic_mapping.py All members: new = 7 incomplete = 6 invalid = 5 wont_fix = 4 in_progress = 3 fix_committed = 2 fix_released = 1
非整数成员值
枚举成员值不限于整数。实际上,任何类型的对象都可以与成员相关联。如果值是元组,则成员将作为单独的参数传递给__init__()。
enum_tuple_values.py
import enum class BugStatus(enum.Enum): new = (7, ['incomplete', 'invalid', 'wont_fix', 'in_progress']) incomplete = (6, ['new', 'wont_fix']) invalid = (5, ['new']) wont_fix = (4, ['new']) in_progress = (3, ['new', 'fix_committed']) fix_committed = (2, ['in_progress', 'fix_released']) fix_released = (1, ['new']) def __init__(self, num, transitions): self.num = num self.transitions = transitions def can_transition(self, new_state): return new_state.name in self.transitions print('Name:', BugStatus.in_progress) print('Value:', BugStatus.in_progress.value) print('Custom attribute:', BugStatus.in_progress.transitions) print('Using attribute:', BugStatus.in_progress.can_transition(BugStatus.new))
在此示例中,每个成员值是一个元组,其中包含数字ID(例如可能存储在数据库中)和远离当前状态的有效转换列表。
$ python3 enum_tuple_values.py Name: BugStatus.in_progress Value: (3, ['new', 'fix_committed']) Custom attribute: ['new', 'fix_committed'] Using attribute: True
对于更复杂的情况,元组可能变得笨拙。由于成员值可以是任何类型的对象,因此字典可用于存在大量单独属性以跟踪每个枚举值的情况。复数值直接传递给 __init__()除了以外的唯一参数self。
enum_complex_values.py
import enum class BugStatus(enum.Enum): new = { 'num': 7, 'transitions': [ 'incomplete', 'invalid', 'wont_fix', 'in_progress', ], } incomplete = { 'num': 6, 'transitions': ['new', 'wont_fix'], } invalid = { 'num': 5, 'transitions': ['new'], } wont_fix = { 'num': 4, 'transitions': ['new'], } in_progress = { 'num': 3, 'transitions': ['new', 'fix_committed'], } fix_committed = { 'num': 2, 'transitions': ['in_progress', 'fix_released'], } fix_released = { 'num': 1, 'transitions': ['new'], } def __init__(self, vals): self.num = vals['num'] self.transitions = vals['transitions'] def can_transition(self, new_state): return new_state.name in self.transitions print('Name:', BugStatus.in_progress) print('Value:', BugStatus.in_progress.value) print('Custom attribute:', BugStatus.in_progress.transitions) print('Using attribute:', BugStatus.in_progress.can_transition(BugStatus.new))
此示例使用字典而不是元组表示与上一示例相同的数据。
$ python3 enum_complex_values.py Name: BugStatus.in_progress Value: {'num': 3, 'transitions': ['new', 'fix_committed']} Custom attribute: ['new', 'fix_committed'] Using attribute: True
相关推荐
- 每天一个 Python 库:datetime 模块全攻略,时间操作太丝滑!
-
在日常开发中,时间处理是绕不开的一块,比如:生成时间戳比较两个时间差转换为可读格式接口传参/前端展示/日志记录今天我们就用一个案例+代码+思维导图,带你完全搞定datetime模块的用法!...
- 字节跳动!2023全套Python入门笔记合集
-
学完python出来,已经工作3年啦,最近有很多小伙伴问我,学习python有什么用其实能做的有很多可以提高工作效率增强逻辑思维还能做爬虫网站数据分析等等!!最近也是整理了很多适合零基...
- 为什么你觉得Matplotlib用起来困难?因为你还没看过这个思维导图
-
前言Matplotlib是一个流行的Python库,可以很容易地用于创建数据可视化。然而,设置数据、参数、图形和绘图在每次执行新项目时都可能变得非常混乱和繁琐。而且由于应用不同,我们不知道选择哪一个图...
- Python新手必看!30分钟搞懂break/continue(附5个实战案例)
-
一、跳转语句的使命当程序需要提前结束循环或跳过特定迭代时,break和continue就是你的代码急刹按钮和跳步指令。就像在迷宫探险中:break=发现出口立即离开continue=跳过陷阱继续前进二...
- 刘心向学(24)Python中的数据类(python中5种简单的数据类型)
-
分享兴趣,传播快乐,增长见闻,留下美好!亲爱的您,这里是LearningYard新学苑。今天小编为大家带来文章“刘心向学(24)Python中的数据类”欢迎您的访问。Shareinterest,...
- 刘心向学(25)Python中的虚拟环境(python虚拟环境安装和配置)
-
分享兴趣,传播快乐,增长见闻,留下美好!亲爱的您,这里是LearningYard新学苑。今天小编为大家带来文章“刘心向学(25)Python中的虚拟环境”欢迎您的访问。Shareinte...
- 栋察宇宙(八):Python 中的 wordcloud 库学习介绍
-
分享乐趣,传播快乐,增长见识,留下美好。亲爱的您,这里是LearingYard学苑!今天小编为大家带来“Python中的wordcloud库学习介绍”欢迎您的访问!Sharethefun,...
- AI在用|ChatGPT、Claude 3助攻,1分钟GET高颜值思维导图
-
机器之能报道编辑:Cardinal以大模型、AIGC为代表的人工智能浪潮已经在悄然改变着我们生活及工作方式,但绝大部分人依然不知道该如何使用。因此,我们推出了「AI在用」专栏,通过直观、有趣且简洁的人...
- 使用DeepSeek + Python开发AI思维导图应用,非常强!
-
最近基于Deepseek+PythonWeb技术开发了一个AI对话自动生成思维导图的应用,用来展示下如何基于低门槛的Python相关技术栈,高效结合deepseek实现从应用场景到实际应用的快速落地...
- 10幅思维导图告诉你 - Python 核心知识体系
-
首先,按顺序依次展示了以下内容的一系列思维导图:基础知识,数据类型(数字,字符串,列表,元组,字典,集合),条件&循环,文件对象,错误&异常,函数,模块,面向对象编程;接着,结合这些思维导图主要参考的...
- Python基础核心思维导图,让你轻松入门
-
Python基础核心思维导图【高清图文末获取】学习路线图就给大家看到这里了,需要的小伙伴下方获取获取方式看下方图片...
- Python基础核心思维导图,学会事半功倍
-
Python基础核心思维导图【高清图文末获取】学习路线图就给大家看到这里了,需要的小伙伴下方获取获取方式看下方图片...
- 硬核!288页Python核心知识笔记(附思维导图,建议收藏)
-
今天就给大家分享一份288页Python核心知识笔记,相较于部分朋友乱糟糟的笔记,这份笔记更够系统地总结相关知识,巩固Python知识体系。文末获取完整版PDF该笔记学习思维导图:目录内容展示【领取方...
- Python学习知识思维导图(高效学习)
-
Python学习知识思维导图python基础知识python数据类型条件循环列表元组字典集合字符串序列函数面向对象编程模块错误异常文件对象#python##python自学##编程#...
- 别找了!288页Python核心知识笔记(附思维导图,建议收藏)
-
今天就给大家分享一份288页Python核心知识笔记,相较于部分朋友乱糟糟的笔记,这份笔记更够系统地总结相关知识,巩固Python知识体系。文末获取完整版PDF该笔记学习思维导图:目录内容展示【领取方...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- 每天一个 Python 库:datetime 模块全攻略,时间操作太丝滑!
- 字节跳动!2023全套Python入门笔记合集
- 为什么你觉得Matplotlib用起来困难?因为你还没看过这个思维导图
- Python新手必看!30分钟搞懂break/continue(附5个实战案例)
- 刘心向学(24)Python中的数据类(python中5种简单的数据类型)
- 刘心向学(25)Python中的虚拟环境(python虚拟环境安装和配置)
- 栋察宇宙(八):Python 中的 wordcloud 库学习介绍
- AI在用|ChatGPT、Claude 3助攻,1分钟GET高颜值思维导图
- 使用DeepSeek + Python开发AI思维导图应用,非常强!
- 10幅思维导图告诉你 - Python 核心知识体系
- 标签列表
-
- python计时 (54)
- python安装路径 (54)
- python类型转换 (75)
- python进度条 (54)
- python的for循环 (56)
- python串口编程 (60)
- python写入txt (51)
- python读取文件夹下所有文件 (59)
- java调用python脚本 (56)
- python操作mysql数据库 (66)
- python字典增加键值对 (53)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python qt (52)
- python人脸识别 (54)
- python斐波那契数列 (51)
- python多态 (60)
- python命令行参数 (53)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- centos7安装python (53)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)