关于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 将数据库中的表与面向对象语言中的类建 ...
随机推荐
- PHP : CodeIgniter mysql_real_escape_string 警告
版本 CodeIgniter 3 PHP 5.4 感谢万能的stackoverflow. 得修改CodeIgniter的源码. ./system/database/drivers/mysql/mysq ...
- 9.CSMA_CD协议
先听再说,边听边说 载波监听多点接入/碰撞检测CSMA/CD( carrier sense multiple access with collision detection) CD:碰撞检测(冲突检测 ...
- 记IntelliJ IDEA创建spring mvc一次坑爹的操作!!!!
本人刚开始学习spring mvc,遇到一问题,现在分享一下. 点击Next,创建项目完成,你会发现缺少很多东西. lib文件没有,里面的jar更没有.applicationContext.xml和d ...
- GitHub 热点速览 Vol.29:程序员资料大全
作者:HelloGitHub-小鱼干 摘要:有什么资料比各种大全更吸引人的呢?先马为敬,即便日后"挺尸"收藏夹,但是每个和程序相关的大全项目都值得一看.比如国内名为小傅哥整理的 J ...
- Nginx使用SSL模块配置https
背景 开发微信小程序,需要https域名,因此使用Nginx的SSL模块配置https 步骤 一.去域名管理商(如腾讯云.阿里云等)申请CA证书 二.在Nginx中配置,一般情况下域名管理商会提供配置 ...
- CSS和JS实现文本溢出显示省略号
本文记录实现文本溢出显示省略号的几种方式. 单行文本 三行CSS代码实现: overflow: hidden; // 文本溢出隐藏 text-overflow: ellipsis; // 显示省略号 ...
- MySQL(一)简介与入门
一.数据库简介 这个博客详细介绍:http://www.cnblogs.com/progor/p/8729798.html 二.MySQL的安装 这个博客详细介绍:https://blog.csdn. ...
- android 6.0三星5.1.1Root
现在google是越来越不给我们留活路了… 从android 6.0开始, 三星的5.1.1开始. 默认都开启了data分区的forceencryption, 也就是强制加密. 也开启了/system ...
- 前端学习(六):body标签(四)
进击のpython ***** 前端学习--body标签 关于前面的都是大部分的标签内容 但是就像衣服一样,除了要有,还要放到适当的位置 我们先来看看一下网页的布局: 就可以看出来,网页都是一块一块的 ...
- Html5 表单元素基础
表单元素 1.定义: 表单是提供让读者在网页上输入,勾选和选取数据,以便提交给服务器数据库的工具.(邮箱注册,用户登录,调查问卷等) 2.表单元素(下拉框,输入框……) 3.表单主结构: <fo ...