关于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. coding如何绑定二次验证码_虚拟MFA_两步验证_身份验证?

    Coding.net 是一个面向开发者的云端开发平台,提供 Git/SVN 代码托管.任务管理.在线 WebIDE.Cloud Studio.开发协作.文件管理.Wiki 管理.提供个人服务及企业管理 ...

  2. Flutter.. 两个点语法含义

    在Flutter编程中,会经常用到".."的语法糖,如下 state.clone() ..splashImg = action.img ..famousSentence = act ...

  3. 全栈的自我修养: 0005 Java 包扫描实现和应用(Jar篇)

    全栈的自我修养: 0005 Java 包扫描实现和应用(Jar篇) It's not the altitude, it's the attitude. 决定一切的不是高度而是态度. Table of ...

  4. 大数据(hadoop)

    大数据 一.概述 二.大数据特点 三.大数据部门组织结构 hadoop框架 一.hadoop是什么 Hadoop是一个由Apache基金会所开发的分布式系统基础架构. 主要解决,海量数据的存储和海量数 ...

  5. 1_Java语言概述

    学于尚硅谷开源课程 宋红康老师主讲 感恩 尚硅谷官网:http://www.atguigu.com 尚硅谷b站:https://space.bilibili.com/302417610?from=se ...

  6. 10-Pandas之数据融合(pd.merge()、df.join()、df.combine_first()详解)

    一.pd.merge() pd.merge()的常用参数 参数 说明 left 参与合并的左侧DataFrame right 参与合并的右侧DataFrame how 如何合并.值为{'left',' ...

  7. P4463 [集训队互测2012] calc 拉格朗日插值 dp 多项式分析

    LINK:calc 容易得到一个nk的dp做法 同时发现走不通了 此时可以考虑暴力生成函数. 不过化简那套不太熟 且最后需要求多项式幂级数及多项式exp等难写的东西. 这里考虑观察优化dp的做法. 不 ...

  8. luogu P4590 [TJOI2018]游园会 dp套dp

    LINK:游园会 容易想到 设\(f[i][j][k][l]\)前i个字符 j表示状压的w个字符状态为j 长度<=k 匹配到了NOI的第l个位置的方案数. 不过只能得到30分. 考虑优化 其实优 ...

  9. Ploya定理学习笔记

    由于自己的作息极其不规律导致比赛被打爆了 但是有的时候状态其实还行. 关于Ploya定理其实特别有意思 这里粘一个[dalao的blog](https://blog.csdn.net/lyc16355 ...

  10. [转]Nginx限流配置

    原文:https://www.cnblogs.com/biglittleant/p/8979915.html 作者:biglittleant 1. 限流算法 1.1 令牌桶算法 算法思想是: 令牌以固 ...