笔记-python-lib—data types-enum

1.      enum

Source code: Lib/enum.py

文档:https://docs.python.org/3/library/enum.html#using-auto

枚举类型enum是比较重要的一个数据类型,它是一种数据类型而不是数据结构,我们通常将一组常用的常数声明成枚举类型方便后续的使用。当一个变量有几种可能的取值的时候,我们将它定义为枚举类型。

1.1.    Module Contents

This module defines four enumeration classes that can be used to define unique sets of names and values: Enum, IntEnum, Flag, and IntFlag. It also defines one decorator, unique(), and one helper, auto.

class enum.Enum

Base class for creating enumerated constants. See section Functional API for an alternate construction syntax.

基础类的枚举类,最常用。

class enum.IntEnum

Base class for creating enumerated constants that are also subclasses of int.

class enum.IntFlag

Base class for creating enumerated constants that can be combined using the bitwise operators without losing their IntFlag membership. IntFlag members are also subclasses of int.

class enum.Flag

Base class for creating enumerated constants that can be combined using the bitwise operations without losing their Flag membership.

enum.unique()

Enum class decorator that ensures only one name is bound to any one value.

装饰器,用于保证枚举类中属性值的唯一性;

class enum.auto

Instances are replaced with an appropriate value for Enum members.

1.2.    基础使用

创建enum类

class Gender(Enum):
    a = 1
    b = 2
    c = 3
    d = 4
    e = 5

pr_type(Gender)

pr_type(Gender(1))
pr_type(Gender.b)

<enum 'Gender'> <class
'enum.EnumMeta'>

Gender.a <enum 'Gender'>

Gender.b <enum 'Gender'>

Gender就是一个类,它的类型是enum.EnumMeta

<enum 'Gender'>are enumeration
members (or enum members) and are functionally constants.是enum members,也叫功能常数

可以通过Gender.a或者Gender(1)或Gender[‘a’]引用属性

每个枚举类有两个属性:name,value,对应的是类变量中的属性名和值。

使用构造方法创建类:

from string import ascii_lowercase
ex1 = Enum('ex', (list(ascii_lowercase)))
pr_type(ex1)

print(ex1(3).__repr__())

结果:

<enum 'ex'> <class
'enum.EnumMeta'>

<ex.c: 3>

使用Enum()函数(就是Enum的构造方法)创建枚举类,该构造方法的第一个参数是枚举类的类名;第二个参数是一个元组,用于列出所有枚举值,也可以是可迭代对象;

本例中未给出枚举类的值,这时它会默认从1开始自增。

1.3.   
属性重复

枚举类的enum members不能重复

class S(Enum):
    sq = 2
    sw = 3
    sq = 4

s = S

报错:

TypeError: Attempted to reuse key: 'sq'

但值可以重复:

class S(Enum):
    sq = 2
    sw = 3
    #sq = 4
   
sr = 3

s = S

没有报错。

如果不允许值重复,enum有一个装饰器unique:

@enum.unique
class S(Enum):
    sq = 2
    sw = 3
    #sq = 4
   
sr = 3
s = S

这里产生抛出了一个异常:

ValueError: duplicate values found in
<enum 'S'>: sr -> sw

1.4.   
其它操作

案例对象:

class Shape(Enum):
    SQUARE = 2
    DIAMOND = 1
    CIRCLE = 3
    ALIAS_FOR_SQUARE = 2

1.4.1.  
iteration

>>> list(Shape)

[<Shape.SQUARE: 2>,
<Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]

The special attribute __members__ is
an ordered dictionary mapping names to members. It includes all names defined
in the enumeration, including the aliases:

>>>
for name, member in Shape.__members__.items():

...     name, member

1.4.2.  
planet

枚举类也可能自定义构造和生成方式,下面是一个简单的演示:

If __new__() or __init__() is
defined the value of the enum member will be passed to those methods:

>>>
class Planet(Enum):

...     MERCURY = (3.303e+23, 2.4397e6)

...     VENUS   = (4.869e+24, 6.0518e6)

...     EARTH   = (5.976e+24, 6.37814e6)

...     MARS    = (6.421e+23, 3.3972e6)

...     JUPITER = (1.9e+27,   7.1492e7)

...     SATURN  = (5.688e+26, 6.0268e7)

...     URANUS  = (8.686e+25, 2.5559e7)

...     NEPTUNE = (1.024e+26, 2.4746e7)

...     def __init__(self, mass, radius):

...         self.mass = mass       # in kilograms

...         self.radius = radius   # in meters

...     @property

...     def surface_gravity(self):

...         # universal gravitational constant  (m3 kg-1 s-2)

...         G = 6.67300E-11

...         return G * self.mass / (self.radius * self.radius)

...

>>>
Planet.EARTH.value

(5.976e+24,
6378140.0)

>>>
Planet.EARTH.surface_gravity

9.802652743337129

笔记-python-lib—data types-enum的更多相关文章

  1. Python - 2. Built-in Collection Data Types

    From: http://interactivepython.org/courselib/static/pythonds/Introduction/GettingStartedwithData.htm ...

  2. Python - 1. Built-in Atomic Data Types

    From:http://interactivepython.org/courselib/static/pythonds/Introduction/GettingStartedwithData.html ...

  3. 高性能MySQL笔记-第4章Optimizing Schema and Data Types

    1.Good schema design is pretty universal, but of course MySQL has special implementation details to ...

  4. ExtJS笔记 Ext.data.Types

    This is a static class containing the system-supplied data types which may be given to a Field. Type ...

  5. Data Types in the Kernel &lt;LDD3 学习笔记&gt;

    Data Types in the Kernel Use of Standard C Types /* * datasize.c -- print the size of common data it ...

  6. 数据分析---《Python for Data Analysis》学习笔记【04】

    <Python for Data Analysis>一书由Wes Mckinney所著,中文译名是<利用Python进行数据分析>.这里记录一下学习过程,其中有些方法和书中不同 ...

  7. 数据分析---《Python for Data Analysis》学习笔记【03】

    <Python for Data Analysis>一书由Wes Mckinney所著,中文译名是<利用Python进行数据分析>.这里记录一下学习过程,其中有些方法和书中不同 ...

  8. 数据分析---《Python for Data Analysis》学习笔记【02】

    <Python for Data Analysis>一书由Wes Mckinney所著,中文译名是<利用Python进行数据分析>.这里记录一下学习过程,其中有些方法和书中不同 ...

  9. 数据分析---《Python for Data Analysis》学习笔记【01】

    <Python for Data Analysis>一书由Wes Mckinney所著,中文译名是<利用Python进行数据分析>.这里记录一下学习过程,其中有些方法和书中不同 ...

  10. 学习笔记之Python for Data Analysis

    Python for Data Analysis, 2nd Edition https://www.safaribooksonline.com/library/view/python-for-data ...

随机推荐

  1. Panda的学习之路(2)——pandas选择数据

    首先定义panda dates=pd.date_range(',periods=6) # print(dates) df=pd.DataFrame(np.arange(24).reshape(6,4) ...

  2. iOS开发之使用 infer静态代码扫描工具

    infer是Facebook 的 Infer 是一个静态分析工具.可以分析 Objective-C, Java 或者 C 代码,报告潜在的问题. 任何人都可以使用 infer 检测应用,可以将严重的 ...

  3. 清除定时器 和 vue 中遇到的定时器setTimeout & setInterval问题

    2019-03更新 找到了更简单的方法,以setinterval为例,各位自行参考 mounted() { const that = this const timer = setInterval(fu ...

  4. redis环境搭建学习笔记

    学习环境为windows.java环境 一.学习教程: 1.菜鸟教程:http://www.runoob.com/redis/redis-tutorial.html 2.redis中文网:http:/ ...

  5. Postman 设置token为全局变量

    在做接口测试的时候,经常会用到不同用户登陆的token,来测试API,通过设置全局的token,这样更便捷: 注意设置的名称必须与你登陆后返回的名称一致,我这里是 AccessToken 1.配置环境 ...

  6. Python3.6打开EAIDK-610开发板(计算机通用)摄像头拍照并保存

    环境:python3.6 代码: import cv2 import os output_dir ='/home/openailab/Desktop/huahui/came/' i = cap = c ...

  7. 事件和方法的区别,以input框的blur事件为例

    1. 我们在原生的js中学到的事件 onblur 2. 使input框失去焦点的方法blur 3. jquery中的方法blur 是当input框失去焦点时触发的回调 三者是不相同的 事件:指的是一个 ...

  8. opencv:图像卷积

    卷积基本概念 C++代码实现卷积 #include <opencv2/opencv.hpp> #include <iostream> using namespace cv; u ...

  9. Java web 会话技术 cookie与session

    一.会话 会话可简单理解为:用户开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话. 会话过程中要解决的一些问题 每个用户在使用浏览器与服务器进行会话的过程 ...

  10. Windows上面搭建FlutterAndroid运行环境

    1.下载安装JDK https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 2.配置J ...