关于python中Enum的个人总结

  1. 初识

    1. 可以通过enum模块导入
  2. 语法

    1. 初始化:

      • 可以通过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

      通过这样就可以初始化并返回一个枚举类。

      1. 关于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

          需要先实例化才能使用。

  3. 结语

    最后,Enum不仅可以是一个好的枚举也可以拿来代替一些繁琐的类、状态、顺序等东西。比如说:`life = Enum('life', 'born baby teenager adult older die')。

    当然,更多的秘密等着你们自己去挖掘。

关于python中Enum的个人总结的更多相关文章

  1. Python中模拟enum枚举类型的5种方法分享

    这篇文章主要介绍了Python中模拟enum枚举类型的5种方法分享,本文直接给出实现代码,需要的朋友可以参考下   以下几种方法来模拟enum:(感觉方法一简单实用) 复制代码代码如下: # way1 ...

  2. Python 中的枚举类型~转

    Python 中的枚举类型 摘要: 枚举类型可以看作是一种标签或是一系列常量的集合,通常用于表示某些特定的有限集合,例如星期.月份.状态等. 枚举类型可以看作是一种标签或是一系列常量的集合,通常用于表 ...

  3. Python中的枚举

    在Python中想要实现枚举功能的方式比较多,可以通过字典这一数据结构,利用键与值的对应关系,可以实现枚举的功能. my_Enum={ 'red':1, 'yellow':2, 'blue':3 } ...

  4. Python中使用枚举类

    开发中我们经常定义常量, 其实有更好的方法:为这样的枚举类型定义一个class类型,然后,每个常量都是class的一个唯一实例.Python中提供了Enum类来实现这个功能: from enum im ...

  5. python 枚举Enum

    常量是任何一门语言中都会使用的一种变量类型 如 要表示星期常量,我们可能会直接定义一组变量 JAN = 1 TWO = 2 ... 然后在返回给前端的时候,我们返回的就会是1,2,...这种魔法数字, ...

  6. 数据库MySql在python中的使用

    随着需要存储数据的结构不断复杂化,使用数据库来存储数据是一个必须面临的问题.那么应该如何在python中使用数据库?下面就在本篇博客中介绍一下在python中使用mysql. 首先,本博客已经假定阅读 ...

  7. Python IAQ中文版 - Python中少有人回答的问题

    Python中少有人回答的问题 The Python IAQ: Infrequently Answered Questions 1 Q: 什么是"少有人回答的问题(Infrequently ...

  8. 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 ...

  9. sqlalchemy python中的mysql数据库神器

    在介绍sqlalchemy之前,我们先了解一下ORM. ORM 全称 Object Relational Mapping, 翻译过来叫对象关系映射.也就是说ORM 将数据库中的表与面向对象语言中的类建 ...

随机推荐

  1. LGTB 与 序列

    题目描述 LGTB 有一个长度为 N 的序列 A ,现在他想构造一个新的长度为 N 的序列 B ,使得 B 中的任意两个数都互质.并且他要使 \sum_{1\le i\le N}|A_i-B_i| 最 ...

  2. scratch编程滑雪者游戏教程

    首先我们来看一下效果:​​​​​​​​​​​​​​​​ 我们从演示中能看出4个角色:企鹅.大树.旗子和装饰用的坎,我们通过键盘操控企鹅滑雪躲避树并捡起旗子,现在我们就来看看是怎么编的吧! 首先我们要画 ...

  3. 图灵学院笔记-java虚拟机底层原理

    Table of Contents generated with DocToc 一.java虚拟机概述 二.栈内存解析 2.1 概述 2.2 栈帧内部结构 2.2.1 我们来解析一下compute() ...

  4. Java Web(1)-JavaScript

    一.JavaScript 和 html 代码的结合方式 1. 第一种方式 只需要在 head 标签中,或者在 body 标签中, 使用 script 标签 来书写 JavaScript 代码 < ...

  5. sqlite 显示表内容时乱码,无法正常显示汉字,

    把txt文件另存为时,选择编码为utf-8即可

  6. Django学习路12_objects 方法(all,filter,exclude,order by,values)

    Person.objects.all() 获取全部数据 def get_persons(request): persons = Person.objects.all() # 获取全部数据 contex ...

  7. PHP vsprintf() 函数

    实例 把格式化字符串写入变量中: <?php高佣联盟 www.cgewang.com$number = 9;$str = "Beijing";$txt = vsprintf( ...

  8. 添加entity实体时报错未能找到 EntityFramework.dll

    错误 1 正在编译转换: 未能找到元数据文件“C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools\..\IDE\Enti ...

  9. Ubuntu chmod 命令修改文件chmod读写权限

    Ubuntu chmod 命令可以用来修改文件或文件夹的读写权限 chmod 命令有两种使用方式 一. chmod [u/g/o/a] [+/-/=] [r/w/x] filename [ ]里都代表 ...

  10. java动态代理——jvm指令集基本概念和方法字节码结构的进一步探究及proxy源码分析四

    前文地址 https://www.cnblogs.com/tera/p/13336627.html 本系列文章主要是博主在学习spring aop的过程中了解到其使用了java动态代理,本着究根问底的 ...