PEP 354:Python中的枚举 [英] PEP 354: Enumerations in Python

查看:55
本文介绍了PEP 354:Python中的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Howdy all,


PEP 354:Python中的枚举已被接受为PEP草案。

当前版本可以在线查看:


< URL:http://www.python.org/peps/pep-0354.html>


这是今天的reStructuredText源代码。请讨论它

这里我可以看到人们可能遇到的问题。

PEP:354

标题:Python中的枚举

版本:$修订:42186 $

最后修改日期:$ Date:2006-01-26 11:55:20 +1100(2006年1月26日星期四)$

作者:Ben Finney< be ******** @ benfinney.id.au>

状态:草稿

类型:Standards Track

内容类型:text / x-rst

创建时间:2005年12月20日

Python-Version:2.6

后历史:2005年12月20日

摘要

========


此PEP指定Python的枚举数据类型。

枚举是绑定到

任意唯一值的一组独有的符号名称。枚举中的值可以迭代

并进行比较,但这些值与枚举之外的值没有内在关系



Motivation

==========


枚举的属性对于定义不可变的

相关集非常有用具有已定义序列但不具有固有语义含义的常量值。经典的例子是一周中的几天

(周日到周六)和学校评估等级(''A''到

''D''和''F' )。其他示例包括错误状态值和状态

在定义的过程中。


可以简单地定义其他一些值的序列

基本类型,例如``int``或``str``,代表离散的

任意值。但是,枚举确保这些值与其他值不同,并且没有为这些值定义没有含义的操作

(星期三乘以)。

规格

=============


枚举类型是从序列创建的

类型构造函数的参数::

Howdy all,

PEP 354: Enumerations in Python has been accepted as a draft PEP. The
current version can be viewed online:

<URL:http://www.python.org/peps/pep-0354.html>

Here is the reStructuredText source as it is today. Please discuss it
here so I can see what issues people may have.
PEP: 354
Title: Enumerations in Python
Version: $Revision: 42186 $
Last-Modified: $Date: 2006-01-26 11:55:20 +1100 (Thu, 26 Jan 2006) $
Author: Ben Finney <be********@benfinney.id.au>
Status: Draft
Type: Standards Track
Content-Type: text/x-rst
Created: 20-Dec-2005
Python-Version: 2.6
Post-History: 20-Dec-2005
Abstract
========

This PEP specifies an enumeration data type for Python.

An enumeration is an exclusive set of symbolic names bound to
arbitrary unique values. Values within an enumeration can be iterated
and compared, but the values have no inherent relationship to values
outside the enumeration.
Motivation
==========

The properties of an enumeration are useful for defining an immutable,
related set of constant values that have a defined sequence but no
inherent semantic meaning. Classic examples are days of the week
(Sunday through Saturday) and school assessment grades (''A'' through
''D'', and ''F''). Other examples include error status values and states
within a defined process.

It is possible to simply define a sequence of values of some other
basic type, such as ``int`` or ``str``, to represent discrete
arbitrary values. However, an enumeration ensures that such values
are distinct from any others, and that operations without meaning
("Wednesday times two") are not defined for these values.
Specification
=============

An enumerated type is created from a sequence of arguments to the
type''s constructor::

Weekdays = enum (''sun'',''mon'',''tue'',''wed'',''thu'',''fri'',''sat'')
Grades = enum (''A'',''B'',''C'',''D'',''F'')


没有值的枚举是没有意义的。如果在没有

值参数的情况下调用构造函数,则会引发异常

``EnumEmptyError``。


值是绑定到新枚举对象的属性::

today = Weekdays.mon


值可以比较::

if today == Weekdays.fri:
... print"为周末做好准备


枚举中的值无法进行有意义的比较,除非

,具有来自相同枚举的值。比较操作

函数返回``NotImplemented`` [#CMP-NOTIMPLEMENTED] _当枚举的

值与不是来自

相同的枚举或不同的类型::

gym_night = Weekdays.wed
gym_night .__ cmp __(Weekdays.mon)
1 gym_night .__ cmp __(平日。结婚)
0 gym_night .__ cmp __(Weekdays.fri)
-1 gym_night .__ cmp __(23)
NotImplemented gym_night .__ cmp __(" wed")
NotImplemented gym_night .__ cmp __( Grades.B)
未实现


这允许操作成功,评估为布尔值::

gym_night = Weekdays.wed
gym_night< Weekdays.mon
False gym_night< Weekdays.wed
False gym_night< Weekdays.fri
True gym_night< 23
False gym_night> 23
True gym_night> " WED"
True gym_night> Grades.B
True


将枚举中的值强制转换为``str``会导致为此指定的

字符串构建

枚举时的价值::

gym_night = Weekdays.wed
str(gym_night)
''wed''


枚举中每个值的序列索引通过该值'的'`index``属性导出为

整数::

gym_night = Weekdays.wed
gym_night.index
3

可以迭代枚举,按顺序返回其值

它们是在创建枚举时指定的:

打印[工作日中某天的str(天)]
[''sun'',''mon'',''tue' ',''wed'',''th'',''fri'',''sat'']


枚举中的值是可清除的,可以用作dict

keys ::

plans = {}
计划[Weekdays.sat] ="喂马和曲OT;


枚举的正常用法是为数据类型提供一组可能的

值,然后可以使用这些值映射到其他

有关值的信息::

for report_grade in Grades:
Weekdays = enum(''sun'', ''mon'', ''tue'', ''wed'', ''thu'', ''fri'', ''sat'')
Grades = enum(''A'', ''B'', ''C'', ''D'', ''F'')
Enumerations with no values are meaningless. The exception
``EnumEmptyError`` is raised if the constructor is called with no
value arguments.

The values are bound to attributes of the new enumeration object::
today = Weekdays.mon
The values can be compared::
if today == Weekdays.fri: ... print "Get ready for the weekend"

Values within an enumeration cannot be meaningfully compared except
with values from the same enumeration. The comparison operation
functions return ``NotImplemented`` [#CMP-NOTIMPLEMENTED]_ when a
value from an enumeration is compared against any value not from the
same enumeration or of a different type::
gym_night = Weekdays.wed
gym_night.__cmp__(Weekdays.mon) 1 gym_night.__cmp__(Weekdays.wed) 0 gym_night.__cmp__(Weekdays.fri) -1 gym_night.__cmp__(23) NotImplemented gym_night.__cmp__("wed") NotImplemented gym_night.__cmp__(Grades.B) NotImplemented

This allows the operation to succeed, evaluating to a boolean value::
gym_night = Weekdays.wed
gym_night < Weekdays.mon False gym_night < Weekdays.wed False gym_night < Weekdays.fri True gym_night < 23 False gym_night > 23 True gym_night > "wed" True gym_night > Grades.B True

Coercing a value from an enumeration to a ``str`` results in the
string that was specified for that value when constructing the
enumeration::
gym_night = Weekdays.wed
str(gym_night) ''wed''

The sequence index of each value from an enumeration is exported as an
integer via that value''s ``index`` attribute::
gym_night = Weekdays.wed
gym_night.index 3

An enumeration can be iterated, returning its values in the sequence
they were specified when the enumeration was created::
print [str(day) for day in Weekdays] [''sun'', ''mon'', ''tue'', ''wed'', ''thu'', ''fri'', ''sat'']

Values from an enumeration are hashable, and can be used as dict
keys::
plans = {}
plans[Weekdays.sat] = "Feed the horse"
The normal usage of enumerations is to provide a set of possible
values for a data type, which can then be used to map to other
information about the values::
for report_grade in Grades:



... report_students [report_grade ] = \

... [s为学生的s,如果students.grade == report_grade]

理由 - 考虑的其他设计

=====================================


所有在一个类中

----------------


某些实现具有枚举及其值全部为

单个对象或类的属性。


此PEP指定枚举为容器的设计,并且

值是简单的可比数据。有人认为,尝试将
的所有枚举属性放在一个类中

使设计变得复杂而没有明显的好处。

用于创建元数据的元数据枚举类

---------------------------------------- -


此PEP中指定的枚举是``enum``

类型的实例。一些替代设计将每个枚举实现为其自己的
类,以及用于定义所有

枚举的公共属性的元类。


为每个

枚举创建一个类(而不是实例)的一个动机是允许枚举的子类,扩展和改变现有的枚举。但是,一个类意味着将创建该类的
实例;很难想象

具有一周中的几天的单独实例意味着

类,其中每个实例包含所有日期。这通常导致

让每个班级遵循Singleton模式,这进一步使设计更加复杂。


相比之下,这个PEP指定不希望扩展或修改
的枚举。当然,可以从现有的字符串值创建一个新的

枚举,如果需要,甚至可以使用``enum``类的子类。

与其他类型相关的价值

-----------------------------


有些设计表达了与其他一些值的强烈关系,例如每个枚举值的特定整数或字符串



这导致在上下文中使用这样的值,其中枚举

没有意义,并且不必要地使设计复杂化。在此PEP导出中指定的

枚举值用于创建它们的值,并且可以与任何其他值进行比较,

但是与枚举之外的值进行序列比较是明确没有实现的。

隐藏枚举值的属性

-------- ------------------------------


之前的设计隐藏了枚举值尽可能

关于它们的实现,到不输出字符串

键和序列索引。


本PEP中的设计承认程序经常会发现它很方便知道枚举值'的枚举类型,序列

索引以及为该值指定的字符串键。它们通过

导出枚举值作为属性。

实现

==============


这个设计部分基于来自

Python Cookbook的食谱[#ENUM-RECIPE] _。


PyPI包``enum`` [#ENUM-PACKAGE] _提供了本PEP中描述的数据类型的Python

实现。

参考文献和脚注

========================


... [#CMP-NOTIMPLEMENTED ]

来自比较操作的``NotImplemented``返回值

表示Python解释器尝试替代比较

或其他后备。 $>
< http://docs.python.org/ref/types.html#l2h-29>


... [#ENUM-RECIPE]

Python中的First Class Enums,Zoran Isailovski,

Python Cookbook食谱413486

< http://aspn.activestate.com / ASPN / Cookbook / Python / Recipe / 413486>


... [#ENU M-PACKAGE]

Python包索引,包``enum``

< http://cheeseshop.python.org/pypi/enum/>

版权

=========


本文档已被置于公共领域。



...

本地变量:

模式:缩进文本

缩进标签-mode:nIL

句子结束双倍空间:t

填充栏:70

结束:

-

\ Contentsofsignaturemaysettleduringshipping。 |

` \ |

_o__)|

Ben Finney


... report_students[report_grade] = \
... [s for s in students if students.grade == report_grade]
Rationale -- Other designs considered
=====================================

All in one class
----------------

Some implementations have the enumeration and its values all as
attributes of a single object or class.

This PEP specifies a design where the enumeration is a container, and
the values are simple comparables. It was felt that attempting to
place all the properties of enumeration within a single class
complicates the design without apparent benefit.
Metaclass for creating enumeration classes
------------------------------------------

The enumerations specified in this PEP are instances of an ``enum``
type. Some alternative designs implement each enumeration as its own
class, and a metaclass to define common properties of all
enumerations.

One motivation for having a class (rather than an instance) for each
enumeration is to allow subclasses of enumerations, extending and
altering an existing enumeration. A class, though, implies that
instances of that class will be created; it is difficult to imagine
what it means to have separate instances of a "days of the week"
class, where each instance contains all days. This usually leads to
having each class follow the Singleton pattern, further complicating
the design.

In contrast, this PEP specifies enumerations that are not expected to
be extended or modified. It is, of course, possible to create a new
enumeration from the string values of an existing one, or even
subclass the ``enum`` type if desired.
Values related to other types
-----------------------------

Some designs express a strong relationship to some other value, such
as a particular integer or string, for each enumerated value.

This results in using such values in contexts where the enumeration
has no meaning, and unnecessarily complicates the design. The
enumerated values specified in this PEP export the values used to
create them, and can be compared for equality with any other value,
but sequence comparison with values outside the enumeration is
explicitly not implemented.
Hiding attributes of enumerated values
--------------------------------------

A previous design had the enumerated values hiding as much as possible
about their implementation, to the point of not exporting the string
key and sequence index.

The design in this PEP acknowledges that programs will often find it
convenient to know the enumerated value''s enumeration type, sequence
index, and string key specified for the value. These are exported by
the enumerated value as attributes.
Implementation
==============

This design is based partly on a recipe [#ENUM-RECIPE]_ from the
Python Cookbook.

The PyPI package ``enum`` [#ENUM-PACKAGE]_ provides a Python
implementation of the data types described in this PEP.
References and Footnotes
========================

... [#CMP-NOTIMPLEMENTED]
The ``NotImplemented`` return value from comparison operations
signals the Python interpreter to attempt alternative comparisons
or other fallbacks.
<http://docs.python.org/ref/types.html#l2h-29>

... [#ENUM-RECIPE]
"First Class Enums in Python", Zoran Isailovski,
Python Cookbook recipe 413486
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486>

... [#ENUM-PACKAGE]
Python Package Index, package ``enum``
<http://cheeseshop.python.org/pypi/enum/>
Copyright
=========

This document has been placed in the public domain.


...
Local Variables:
mode: indented-text
indent-tabs-mode: nil
sentence-end-double-space: t
fill-column: 70
End:
--
\ Contentsofsignaturemaysettleduringshipping. |
`\ |
_o__) |
Ben Finney

推荐答案

修订版:42186




Last-Modified:

Last-Modified:


日期:2006-01-26 11 :55:20 +1100(2006年1月26日星期四)
Date: 2006-01-26 11:55:20 +1100 (Thu, 26 Jan 2006)


这篇关于PEP 354:Python中的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆