Python深入浅出分析enum枚举类
作者:Flyme?awei 时间:2022-07-07 15:09:14
枚举类Enum
枚举类,在企业开发中用的比较多
当我们需要定义常量时,一个办法是用大写的变量通过整数来定义,例如月份:
# 当项目中需要使用12个月份时
JAN = 1
FEB = 2
...
NOV = 11
DEC = 12
但是这样的定义的类型是 int
,并且仍然是变量,并且在运算中,无法时时创建对应的值,当然这种指代是以更好的方式去使用变量数值。
这里存在更好的方法是为这样的枚举类型定义一个class
类型,然后,每个常量都是class
的一个唯一实例。Python提供了 Enum
类来实现这个功能。
优化如下
# -*- coding: utf-8 -*-
from enum import Enum
# 枚举中,一个名字对应一个值
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Otc', 'Nov', 'Dec'))
这样我们就获得了 Month
类型的枚举类,可以直接使用 Month.Jan
来引用一个常量,或者枚举它的所有成员通过for
循环进行取值,
Month.__members__
是Month的内置变量,可以打印成员标签,
如果在这个方法调用上.items()
函数所有成员都打印出来,数据类型为元组
for name, member in Month.__members__.items():
print(f'{name} => {member} , {member.value}')+
定义一个颜色常量枚举
# -*- coding: utf-8 -*-
from enum import Enum
# 枚举中 一个一个名字对应一个值
Month = Enum('抬头-Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
print(Month.__members__) # 枚举中的值自动从1开始,不会重复
# 得到三月份的值
print(Month['Mar'].value) # 3
# 根据(2)来获得月份名字
print(Month(2).name) # Feb
# 定义一个颜色的常量枚举
class Color(Enum): # 第二种:自定义一个枚举类
red = 100
green = 200
blue = 300
yellow = 200 # 不允许key相同或者value,如果value重复,根据value取name只能取第一个
print(Color(200)) # Color.green
不允许key相同或者value相同,如果value重复,根据value取name只能取第一个
来源:https://aweia.blog.csdn.net/article/details/125583107
标签:Python,枚举类,enum
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python检测数据类型的方法总结
2022-08-29 22:07:58
![](https://img.aspxhome.com/file/2023/1/65461_0s.png)
给页面 unload 加上效果
2009-03-12 12:32:00
浅谈Python基础之I/O模型
2021-11-17 18:38:03
![](https://img.aspxhome.com/file/2023/1/87671_0s.png)
Python简易版图书管理系统
2022-06-07 21:11:10
交互设计实用指南系列(2) –可及
2010-01-21 12:48:00
![](https://img.aspxhome.com/file/UploadPic/20101/21/sm11-73s.jpg)
关于CSS中字号控制的兼容性研究
2010-01-23 12:48:00
Python argparse模块应用实例解析
2023-08-29 12:44:52
python将音频进行变速的操作方法
2023-10-05 19:04:34
![](https://img.aspxhome.com/file/2023/1/89401_0s.png)
Hello! 404
2010-09-06 13:37:00
![](https://img.aspxhome.com/file/UploadPic/20109/6/google-75s.jpg)
怎么样在网页上读取远程xml的数据
2008-10-10 17:43:00
asp长文章分页显示思路
2007-08-23 13:54:00
一个基于flask的web应用诞生 bootstrap框架美化(3)
2023-12-04 02:30:39
![](https://img.aspxhome.com/file/2023/8/86488_0s.png)
python 绘制场景热力图的示例
2022-01-22 07:03:21
![](https://img.aspxhome.com/file/2023/0/80560_0s.jpg)
盲人站长深恶痛绝的onfocus=”this.blur()”
2011-04-22 12:25:00
linux下安装php扩展memcache的方法
2023-11-21 19:49:02
![](https://img.aspxhome.com/file/2023/4/112714_0s.jpg)
Python实现Pig Latin小游戏实例代码
2022-06-27 04:15:36
JS轮播图中缓动函数的封装
2023-08-22 20:50:11
用asp获取微软安全更新列表的代码 小偷程序
2011-02-24 11:19:00
MySQL出现1067错误如何解决?
2008-09-03 12:25:00
Python使用文件锁实现进程间同步功能【基于fcntl模块】
2022-07-04 17:45:15