关于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 将数据库中的表与面向对象语言中的类建 ...
随机推荐
- vue配置 less 全局变量
在使用Vue开发的过程中,通常会用到一些样式的全局变量,如果在每个组件中引入就太繁琐了,维护性也不好,因此全局引入是个不错的想法.下面以less为例,记录一下全局引入less变量的步骤: 1.首先安装 ...
- IDEA 2020版破解
这期教一下大家如何破解IDEA 最新版破解教程 有以前的idea建议卸载哈~安装最新版的版本 一:我们首先去idea官网下载最新版 下方是idae官网2020最新链接 https://www.jetb ...
- MapReduce之自定义InputFormat
在企业开发中,Hadoop框架自带的InputFormat类型不能满足所有应用场景,需要自定义InputFormat来解决实际问题. 自定义InputFormat步骤如下: (1)自定义一个类继承Fi ...
- Oracle修改表类型方法
有一个表名为tb,字段段名为name,数据类型nchar(20). 1.假设字段数据为空,则不管改为什么字段类型,可以直接执行:alter table tb modify (name nvarchar ...
- javac不是内部或外部命令,也不是可运行的程序或批处理文件的错误解决方法(Windows10/Windows7)
前言:在配置JDK环境变量后,java显示正常,javac则显示javac不是内部或外部命令,也不是可运行的程序或批处理文件.造成javac不是内部或外部命令,也不是可运行的程序或批处理文件的问题一般 ...
- web自动化 -- 三种等待方式
一.强制等待 二.隐式等待 注:隐式等待的作用域是全局,所以一般设置在整局代码的头几行. 如: 三.显示等待 元素存在: 元素可见: 元素可点击: 看到上图源码中有一个 element.is_en ...
- spring学习(一)spring简介
Spring简介: Spring 框架是 Java 应用最广的框架,它的成功来源于理念,而不是技术本身,它的理念包括 IoC (Inversion of Control,控制反转) 和 AOP(Asp ...
- 学python不是一个入门教程就行,学之前你必须知道这些
第一 学习方向:python应用方向很多,必须明确学习方向想 全栈开发:就是web应用开发,是用来写网站后台的数据分析:就是做大数据分析的,数据量级起码是千万级别的,做的是大数据分析网络爬虫:其实属于 ...
- 前端学习(十三):CSS盒子模型
进击のpython ***** 前端学习--CSS盒子模型 在前面的时候也说过,包括分析网页结构的时候,提到了,网页就其实就是一个一个盒子叠起来的 那现在就是有装饰的盒子,难度就变得深刻 所以说为了能 ...
- 遇到的spring问题,或许需要下载新的java jdk
org.springframework.context.support.AbstractApplicationContext