关于python中Enum的个人总结
关于python中Enum的个人总结
初识
- 可以通过enum模块导入
语法
初始化:
- 可以通过
enum_ = Enum('class_name', names,start = 1)来创建,其中names可以是字符串,可以是列表/元组。内部定义为:
def _create_(cls, class_name, names, *, module=None, qualname=None, type=None, start=1):
"""Convenience method to create a new Enum class. `names` can be: * A string containing member names, separated either with spaces or
commas. Values are incremented by 1 from `start`.
* An iterable of member names. Values are incremented by 1 from `start`.
* An iterable of (member name, value) pairs.
* A mapping of member name -> value pairs. """
metacls = cls.__class__
bases = (cls, ) if type is None else (type, cls)
_, first_enum = cls._get_mixins_(bases)
classdict = metacls.__prepare__(class_name, bases) # special processing needed for names?
if isinstance(names, str):
names = names.replace(',', ' ').split()
if isinstance(names, (tuple, list)) and names and isinstance(names[0], str):
original_names, names = names, []
last_values = []
for count, name in enumerate(original_names):
value = first_enum._generate_next_value_(name, start, count, last_values[:])
last_values.append(value)
names.append((name, value)) # Here, names is either an iterable of (name, value) or a mapping.
for item in names:
if isinstance(item, str):
member_name, member_value = item, names[item]
else:
member_name, member_value = item
classdict[member_name] = member_value
enum_class = metacls.__new__(metacls, class_name, bases, classdict) # TODO: replace the frame hack if a blessed way to know the calling
# module is ever developed
if module is None:
try:
module = sys._getframe(2).f_globals['__name__']
except (AttributeError, ValueError, KeyError) as exc:
pass
if module is None:
_make_class_unpicklable(enum_class)
else:
enum_class.__module__ = module
if qualname is not None:
enum_class.__qualname__ = qualname return enum_class通过这样就可以初始化并返回一个枚举类。
关于Enum的元素的使用
通过源码可知:可以通过:enum_(value).vlaue/name,或者sth = enum.name-->sth.name/value,至于为什么,需要查看源码:
class DynamicClassAttribute:
"""Route attribute access on a class to __getattr__. This is a descriptor, used to define attributes that act differently when
accessed through an instance and through a class. Instance access remains
normal, but access to an attribute through a class will be routed to the
class's __getattr__ method; this is done by raising AttributeError. This allows one to have properties active on an instance, and have virtual
attributes on the class with the same name (see Enum for an example). """
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
# next two lines make DynamicClassAttribute act the same as property
self.__doc__ = doc or fget.__doc__
self.overwrite_doc = doc is None
# support for abstract methods
self.__isabstractmethod__ = bool(getattr(fget, '__isabstractmethod__', False)) def __get__(self, instance, ownerclass=None):
if instance is None:
if self.__isabstractmethod__:
return self
raise AttributeError()
elif self.fget is None:
raise AttributeError("unreadable attribute")
return self.fget(instance) def __set__(self, instance, value):
if self.fset is None:
raise AttributeError("can't set attribute")
self.fset(instance, value) def __delete__(self, instance):
if self.fdel is None:
raise AttributeError("can't delete attribute")
self.fdel(instance) def getter(self, fget):
fdoc = fget.__doc__ if self.overwrite_doc else None
result = type(self)(fget, self.fset, self.fdel, fdoc or self.__doc__)
result.overwrite_doc = self.overwrite_doc
return result def setter(self, fset):
result = type(self)(self.fget, fset, self.fdel, self.__doc__)
result.overwrite_doc = self.overwrite_doc
return result def deleter(self, fdel):
result = type(self)(self.fget, self.fset, fdel, self.__doc__)
result.overwrite_doc = self.overwrite_doc
return result
需要先实例化才能使用。
- 可以通过
结语
最后,Enum不仅可以是一个好的枚举也可以拿来代替一些繁琐的类、状态、顺序等东西。比如说:`life = Enum('life', 'born baby teenager adult older die')。
当然,更多的秘密等着你们自己去挖掘。
关于python中Enum的个人总结的更多相关文章
- Python中模拟enum枚举类型的5种方法分享
这篇文章主要介绍了Python中模拟enum枚举类型的5种方法分享,本文直接给出实现代码,需要的朋友可以参考下 以下几种方法来模拟enum:(感觉方法一简单实用) 复制代码代码如下: # way1 ...
- Python 中的枚举类型~转
Python 中的枚举类型 摘要: 枚举类型可以看作是一种标签或是一系列常量的集合,通常用于表示某些特定的有限集合,例如星期.月份.状态等. 枚举类型可以看作是一种标签或是一系列常量的集合,通常用于表 ...
- Python中的枚举
在Python中想要实现枚举功能的方式比较多,可以通过字典这一数据结构,利用键与值的对应关系,可以实现枚举的功能. my_Enum={ 'red':1, 'yellow':2, 'blue':3 } ...
- Python中使用枚举类
开发中我们经常定义常量, 其实有更好的方法:为这样的枚举类型定义一个class类型,然后,每个常量都是class的一个唯一实例.Python中提供了Enum类来实现这个功能: from enum im ...
- python 枚举Enum
常量是任何一门语言中都会使用的一种变量类型 如 要表示星期常量,我们可能会直接定义一组变量 JAN = 1 TWO = 2 ... 然后在返回给前端的时候,我们返回的就会是1,2,...这种魔法数字, ...
- 数据库MySql在python中的使用
随着需要存储数据的结构不断复杂化,使用数据库来存储数据是一个必须面临的问题.那么应该如何在python中使用数据库?下面就在本篇博客中介绍一下在python中使用mysql. 首先,本博客已经假定阅读 ...
- Python IAQ中文版 - Python中少有人回答的问题
Python中少有人回答的问题 The Python IAQ: Infrequently Answered Questions 1 Q: 什么是"少有人回答的问题(Infrequently ...
- Json schema 以及在python中的jsonschema
目录 1. JSON Schema简介 2. JSON Schema关键字详解 2.1 $schema 2.2 title和description 2.3 type 3 type常见取值 3.1 当t ...
- sqlalchemy python中的mysql数据库神器
在介绍sqlalchemy之前,我们先了解一下ORM. ORM 全称 Object Relational Mapping, 翻译过来叫对象关系映射.也就是说ORM 将数据库中的表与面向对象语言中的类建 ...
随机推荐
- UVA 10653.Prince and Princess
题目 In an n * n chessboard, Prince and Princess plays a game. The squares in the chessboard are numbe ...
- metaspolit下UAC提权以及日志清除
在获得webshell时但权限不够大,这时候为了完全获得受害者机器的权限,使用msf进行后渗透. 一.获取Meterpreter会话 Meterpreter 是msf的一个payload,目标执行之后 ...
- css初始化表(normalize.css)
为什么要初始化CSS? 建站老手都知道,这是为了考虑到浏览器的兼容问题,其实不同浏览器对有些标签的默认值是不同的,如果没对CSS初始化往往会出现浏览器之间的页面差异.当然,初始化样式会对SEO有一定的 ...
- 根据 Promise/A+ 和 ES6 规范,实现 Promise(附详细测试)
Promise 源码 https://github.com/lfp1024/promise promise-a-plus const PENDING = 'PENDING' const REJECTE ...
- go test 测试用例那些事(二) mock
关于go的单元测试,之前有写过一篇帖子go test测试用例那些事,但是没有说go官方的库mock,很有必要单独说一下这个库,和他的实现原理. mock主要的功能是对接口的模拟,需要在写代码的时候定义 ...
- logrotate nginx日志切割
1.安装 centos: yum -y install logrotate ubuntu: apt-get install -y logrotate 2. 配置文件 /etc/logrotate.co ...
- Redis服务之常用配置(一)
上一篇博客聊了下redis的简介以及redis的yum安装和源码编译安装需要注意到问题,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/13378138.html ...
- Python网络编程基础 PDF 完整超清版|网盘链接内附提取码下载|
点此获取下载地址提取码:y9u5 Python网络编程最好新手入门书籍!175个详细案例,事实胜于雄辩,Sockets.DNS.Web Service.FTP.Email.SMTP.POP.IMAP. ...
- 线程_进程间通信Queue合集
# Queue的工作原理 from multiprocessing import Queue q = Queue(3)#初始化一个Queue对象,最多可接收3条put消息 q.put("In ...
- PHP cal_from_jd() 函数
------------恢复内容开始------------ 实例 把儒略日计数转换为格利高里历法的日期: <?php$d=unixtojd(mktime(0,0,0,6,20,2007));p ...