热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

开发笔记:Enum的使用记录。

篇首语:本文由编程笔记#小编为大家整理,主要介绍了Enum的使用记录。相关的知识,希望对你有一定的参考价值。参考链接:Python_枚举廖雪峰的使

篇首语:本文由编程笔记#小编为大家整理,主要介绍了Enum的使用记录。相关的知识,希望对你有一定的参考价值。


参考链接:Python_枚举

     廖雪峰的使用枚举类

 

我自己的使用感受,枚举就像定义了一套变量赋值关系,这套赋值关系就一个对象,你可以通过对象里面的key或者value来找到对象本身。

使用起来还时蛮有意思的。

 

使用中,你可以通过创建类,继承使用。或者直接通过Enum(‘xx‘,‘xxx xxx xxx‘)来使用。

首先通过创建类来使用:


In [71]: class My_Enum(Enum):
...: name = ‘sidian‘
...: age = 18
...: adde = ‘hangzhou‘
...:
In [72]: My_Enum.name # 通过类属性来知道关系对象
Out[72]:
In [73]: dir(My_Enum.name) # 产看对象的一些属性,竟然没有看到那么的属性
Out[73]: [‘__class__‘, ‘__doc__‘, ‘__module__‘, ‘value‘]
In [74]: My_Enum.name.value # 查看对象的值
Out[74]: ‘sidian‘
In [75]: My_Enum(‘sidian‘) # 通过实例化值来找到关系对象实例
Out[75]:
In [76]: x = My_Enum(‘sidian‘)
In [77]: x
Out[77]:
In [78]: dir(x)
Out[78]: [‘__class__‘, ‘__doc__‘, ‘__module__‘, ‘value‘]
In [79]: x.name # 虽然没有name属性,但从name属性还时拿到了关系对象的name
Out[79]: ‘name‘
In [80]: dir(My_Enum)
Out[80]: [‘__class__‘, ‘__doc__‘, ‘__members__‘, ‘__module__‘, ‘adde‘, ‘age‘, ‘name‘]
In [81]: My_Enum.__members__ # 通过__members__属性可以看到内部的成员为不可变的字典,key为类属性的字符串形式,value为关系对象。
Out[81]:
mappingproxy({‘name‘: ,
‘age‘: ,
‘adde‘: })
In [82]:

 

还有一种就是直接实例化Enum类


In [88]: my_son = Enum(‘son‘,‘dabao erbao sanbao‘)
In [89]: my_son # 通过实例化创建对象
Out[89]:
In [90]: My_Enum # 对前面通过继承的类名调用,发现该类名已经是Enum的实例,Enum给我的感觉像类元。
Out[90]:
In [91]: my_son.__members__ # Enum里面的参数,第一个是实例后的对象名称,后面的参数空格会自动切割,然后自动给分割后的变量名复制,复制初始值从1开始
Out[91]:
mappingproxy({‘dabao‘: ,
‘erbao‘: ,
‘sanbao‘: })
In [92]: my_son(2) # 通过值寻找关系对象
Out[92]:
In [93]: my_son(2).name
Out[93]: ‘erbao‘
In [94]: my_love = Enum(‘love‘,[‘l1‘,‘l2‘]) # 实例化的第二个参数也可以通过列表进行传入
In [95]: my_love
Out[95]:
In [96]: my_love(1)
Out[96]:
In [97]: my_love(2)
Out[97]:
In [98]:

 


In [100]: Enum?
Init signature: Enum(value, names=None, *, module=None, qualname=None, type=None, start=1)
Docstring:
Generic enumeration.
Derive from this class to define new enumerations.
File: /usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/enum.py
Type: EnumMeta
Subclasses: IntEnum, Flag, Purpose, _SendfileMode, SortKey, s, Color, 12, Status, Gender, ...
In [101]:

 下面上原码


Init signature: Enum(value, names=None, *, module=None, qualname=None, type=None, start=1)
Source:
class Enum(metaclass=EnumMeta):
"""Generic enumeration.
Derive from this class to define new enumerations.
"""
def __new__(cls, value):
# all enum instances are actually created during class construction
# without calling this method; this method is called by the metaclass‘
# __call__ (i.e. Color(3) ), and by pickle
if type(value) is cls:
# For lookups like Color(Color.RED)
return value
# by-value search for a matching enum member
# see if it‘s in the reverse mapping (for hashable values)
try:
return cls._value2member_map_[value]
except KeyError:
# Not found, no need to do long O(n) search
pass
except TypeError:
# not there, now do long search -- O(n) behavior
for member in cls._member_map_.values():
if member._value_ == value:
return member
# still not found -- try _missing_ hook
try:
exc = None
result = cls._missing_(value)
except Exception as e:
exc = e
result = None
if isinstance(result, cls):
return result
else:
ve_exc = ValueError("%r is not a valid %s" % (value, cls.__name__))
if result is None and exc is None:
raise ve_exc
elif exc is None:
exc = TypeError(
‘error in %s._missing_: returned %r instead of None or a valid member‘
% (cls.__name__, result)
)
exc.__context__ = ve_exc
raise exc
def _generate_next_value_(name, start, count, last_values):
for last_value in reversed(last_values):
try:
return last_value + 1
except TypeError:
pass
else:
return start
@classmethod
def _missing_(cls, value):
raise ValueError("%r is not a valid %s" % (value, cls.__name__))
def __repr__(self):
return "<%s.%s: %r>" % (
self.__class__.__name__, self._name_, self._value_)
def __str__(self):
return "%s.%s" % (self.__class__.__name__, self._name_)
def __dir__(self):
added_behavior = [
m
for cls in self.__class__.mro()
for m in cls.__dict__
if m[0] != ‘_‘ and m not in self._member_map_
]
return ([‘__class__‘, ‘__doc__‘, ‘__module__‘] + added_behavior)
def __format__(self, format_spec):
# mixed-in Enums should use the mixed-in type‘s __format__, otherwise
# we can get strange results with the Enum name showing up instead of
# the value
# pure Enum branch
if self._member_type_ is object:
cls = str
val = str(self)
# mix-in branch
else:
cls = self._member_type_
val = self._value_
return cls.__format__(val, format_spec)
def __hash__(self):
return hash(self._name_)
def __reduce_ex__(self, proto):
return self.__class__, (self._value_, )
# DynamicClassAttribute is used to provide access to the `name` and
# `value` properties of enum members while keeping some measure of
# protection from modification, while still allowing for an enumeration
# to have members named `name` and `value`. This works because enumeration
# members are not set directly on the enum class -- __getattr__ is
# used to look them up.
@DynamicClassAttribute
def name(self):
"""The name of the Enum member."""
return self._name_
@DynamicClassAttribute
def value(self):
"""The value of the Enum member."""
return self._value_
@classmethod
def _convert(cls, name, module, filter, source=None):
"""
Create a new Enum subclass that replaces a collection of global constants
"""
# convert all constants from source (or module) that pass filter() to
# a new Enum called name, and export the enum and its members back to
# module;
# also, replace the __reduce_ex__ method so unpickling works in
# previous Python versions
module_globals = vars(sys.modules[module])
if source:
source = vars(source)
else:
source = module_globals
# We use an OrderedDict of sorted source keys so that the
# _value2member_map is populated in the same order every time
# for a consistent reverse mapping of number to name when there
# are multiple names for the same number rather than varying
# between runs due to hash randomization of the module dictionary.
members = [
(name, source[name])
for name in source.keys()
if filter(name)]
try:
# sort by value
members.sort(key=lambda t: (t[1], t[0]))
except TypeError:
# unless some values aren‘t comparable, in which case sort by name
members.sort(key=lambda t: t[0])
cls = cls(name, members, module=module)
cls.__reduce_ex__ = _reduce_ex_by_name
module_globals.update(cls.__members__)
module_globals[name] = cls
return cls
File: /usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/enum.py
Type: EnumMeta
Subclasses: IntEnum, Flag, Purpose, _SendfileMode, SortKey, s, Color, 12, Status, Gender, ...
(END)


推荐阅读
  • Python爬虫中使用正则表达式的方法和注意事项
    本文介绍了在Python爬虫中使用正则表达式的方法和注意事项。首先解释了爬虫的四个主要步骤,并强调了正则表达式在数据处理中的重要性。然后详细介绍了正则表达式的概念和用法,包括检索、替换和过滤文本的功能。同时提到了re模块是Python内置的用于处理正则表达式的模块,并给出了使用正则表达式时需要注意的特殊字符转义和原始字符串的用法。通过本文的学习,读者可以掌握在Python爬虫中使用正则表达式的技巧和方法。 ... [详细]
  • 本文介绍了在处理不规则数据时如何使用Python自动提取文本中的时间日期,包括使用dateutil.parser模块统一日期字符串格式和使用datefinder模块提取日期。同时,还介绍了一段使用正则表达式的代码,可以支持中文日期和一些特殊的时间识别,例如'2012年12月12日'、'3小时前'、'在2012/12/13哈哈'等。 ... [详细]
  • 本文整理了315道Python基础题目及答案,帮助读者检验学习成果。文章介绍了学习Python的途径、Python与其他编程语言的对比、解释型和编译型编程语言的简述、Python解释器的种类和特点、位和字节的关系、以及至少5个PEP8规范。对于想要检验自己学习成果的读者,这些题目将是一个不错的选择。请注意,答案在视频中,本文不提供答案。 ... [详细]
  • VScode格式化文档换行或不换行的设置方法
    本文介绍了在VScode中设置格式化文档换行或不换行的方法,包括使用插件和修改settings.json文件的内容。详细步骤为:找到settings.json文件,将其中的代码替换为指定的代码。 ... [详细]
  • Commit1ced2a7433ea8937a1b260ea65d708f32ca7c95eintroduceda+Clonetraitboundtom ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • Oracle seg,V$TEMPSEG_USAGE与Oracle排序的关系及使用方法
    本文介绍了Oracle seg,V$TEMPSEG_USAGE与Oracle排序之间的关系,V$TEMPSEG_USAGE是V_$SORT_USAGE的同义词,通过查询dba_objects和dba_synonyms视图可以了解到它们的详细信息。同时,还探讨了V$TEMPSEG_USAGE的使用方法。 ... [详细]
  • JDK源码学习之HashTable(附带面试题)的学习笔记
    本文介绍了JDK源码学习之HashTable(附带面试题)的学习笔记,包括HashTable的定义、数据类型、与HashMap的关系和区别。文章提供了干货,并附带了其他相关主题的学习笔记。 ... [详细]
  • Whatsthedifferencebetweento_aandto_ary?to_a和to_ary有什么区别? ... [详细]
  • 本文介绍了在MFC下利用C++和MFC的特性动态创建窗口的方法,包括继承现有的MFC类并加以改造、插入工具栏和状态栏对象的声明等。同时还提到了窗口销毁的处理方法。本文详细介绍了实现方法并给出了相关注意事项。 ... [详细]
  • Hibernate延迟加载深入分析-集合属性的延迟加载策略
    本文深入分析了Hibernate延迟加载的机制,特别是集合属性的延迟加载策略。通过延迟加载,可以降低系统的内存开销,提高Hibernate的运行性能。对于集合属性,推荐使用延迟加载策略,即在系统需要使用集合属性时才从数据库装载关联的数据,避免一次加载所有集合属性导致性能下降。 ... [详细]
  • 本文详细介绍了使用C#实现Word模版打印的方案。包括添加COM引用、新建Word操作类、开启Word进程、加载模版文件等步骤。通过该方案可以实现C#对Word文档的打印功能。 ... [详细]
  • Ihaveaworkfolderdirectory.我有一个工作文件夹目录。holderDir.glob(*)>holder[ProjectOne, ... [详细]
author-avatar
journeylis-1998_246
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有