笔记-python-lib—data types-enum
笔记-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的更多相关文章
- Python - 2. Built-in Collection Data Types
From: http://interactivepython.org/courselib/static/pythonds/Introduction/GettingStartedwithData.htm ...
- Python - 1. Built-in Atomic Data Types
From:http://interactivepython.org/courselib/static/pythonds/Introduction/GettingStartedwithData.html ...
- 高性能MySQL笔记-第4章Optimizing Schema and Data Types
1.Good schema design is pretty universal, but of course MySQL has special implementation details to ...
- ExtJS笔记 Ext.data.Types
This is a static class containing the system-supplied data types which may be given to a Field. Type ...
- Data Types in the Kernel <LDD3 学习笔记>
Data Types in the Kernel Use of Standard C Types /* * datasize.c -- print the size of common data it ...
- 数据分析---《Python for Data Analysis》学习笔记【04】
<Python for Data Analysis>一书由Wes Mckinney所著,中文译名是<利用Python进行数据分析>.这里记录一下学习过程,其中有些方法和书中不同 ...
- 数据分析---《Python for Data Analysis》学习笔记【03】
<Python for Data Analysis>一书由Wes Mckinney所著,中文译名是<利用Python进行数据分析>.这里记录一下学习过程,其中有些方法和书中不同 ...
- 数据分析---《Python for Data Analysis》学习笔记【02】
<Python for Data Analysis>一书由Wes Mckinney所著,中文译名是<利用Python进行数据分析>.这里记录一下学习过程,其中有些方法和书中不同 ...
- 数据分析---《Python for Data Analysis》学习笔记【01】
<Python for Data Analysis>一书由Wes Mckinney所著,中文译名是<利用Python进行数据分析>.这里记录一下学习过程,其中有些方法和书中不同 ...
- 学习笔记之Python for Data Analysis
Python for Data Analysis, 2nd Edition https://www.safaribooksonline.com/library/view/python-for-data ...
随机推荐
- Codeforces Round #613 (Div. 2)D(贪心,分治)
构造两颗深度为30的字典树(根节点分别是0和1),结点只有0和1,从根节点向下DFS,贪心取答案. #define HAVE_STRUCT_TIMESPEC #include<bits/stdc ...
- Go_channel
通道可以被认为是Goroutines通信的管道.类似于管道中的水从一端到另一端的流动,数据可以从一端发送到另一端,通过通道接收. 在前面讲Go语言的并发时候,我们就说过,当多个Goroutine想实现 ...
- Go_ioutil包
1. ioutil包的方法 // Discard 是一个 io.Writer 接口,调用它的 Write 方法将不做任何事情 // 并且始终成功返回. var Discard io.Writer = ...
- [经验] Java 使用 netty 框架, 向 Unity 客户端的 C# 实现通信[2]
在前一篇文章中, 我们实现了从Java netty 服务端到 unity 客户端的通讯, 但是在过程中也发现有一些问题是博主苦苦无法解决的, 但是还好终于有些问题还是被我找刀方法解决了, 现在把这些解 ...
- C语言报错:“gets”: 找不到标识符。解决方法
C语言报错:“gets”: 找不到标识符. 把“gets”改成“gets_s”即可.
- 隐藏pyqt中调用matplotlib图片中的工具栏
方法: # pyqtgraph使用matplotlib import pyqtgraph.widgets.MatplotlibWidget as mw a_plt = mw.MatplotlibWid ...
- 树莓派安装raspbian并配置开发环境
1.烧录系统 首先准备好我们要烧录的raspbian系统,可以在树莓派官网中下载https://www.raspberrypi.org/downloads/ 这里我们选择 2018-11-13-ras ...
- Educational Codeforces Round 77 (Rated for Div. 2)D(二分+贪心)
这题二分下界是0,所以二分写法和以往略有不同,注意考虑所有区间,并且不要死循环... #define HAVE_STRUCT_TIMESPEC #include<bits/stdc++.h> ...
- ios 用touchend事件 pc用click touchend击穿
var clickEvent = (function() { if ('ontouchend' in document.documentElement === true) return 'touche ...
- SQLite3创建表及操作
SQLite 创建表 SQLite 的 CREATE TABLE 语句用于在任何给定的数据库创建一个新表.创建基本表,涉及到命名表.定义列及每一列的数据类型. 语法 CREATE TABLE 语句的基 ...