这种“枚举”成语如何运作?

时间:2014-03-09 01:29:56

标签: python python-2.7 enumeration

我已经使用了一段时间 - 我无法回忆起我发现它的位置:

#####
#  An enumeration is handy for defining types of event 
#  (which otherwise would messily be just random strings)

def enum(**enums):
    return type('Enum', (), enums)

#####
#   The control events that the Controller can process
#   Usually this would be in a module imported by each of M, V and C
#   These are the possible values for the "event" parameter of an APP_EVENT message

AppEvents = enum(APP_EXIT = 0,
                 CUSTOMER_DEPOSIT = 1,
                 CUSTOMER_WITHDRAWAL = 2)

它是如何工作的?

1 个答案:

答案 0 :(得分:3)

以这种方式调用时,type动态声明一个类型。来自docs

  

使用三个参数,返回一个新的类型对象。 这实际上是类语句的动态形式。名称字符串是类名,并成为名称属性;基元元组列出基类并成为基础属性; dict字典是包含类体定义的命名空间,并成为 dict 属性。

所以类型名称是' Enum'并且没有基类。

enum函数有一个**enums参数,它接受所有命名参数并将它们放入字典对象中。

在您的情况下,enums变量是

{
    'APP_EXIT': 0,
    'CUSTOMER_DEPOSIT':  1,
    'CUSTOMER_WITHDRAWAL': 2,
}

那些成为返回类型的属性。


仅供参考,{3}已添加到Python 3.4和Enum到2.4+。 (另见backported)。