我已经用了很长一段时间了-我想不起来我是在哪里找到的:
#####
# 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)
它怎麽工作?
发布于 2014-03-08 17:36:48
当以这种方式调用时,type
会动态声明一个类型。来自文档
使用三个参数,返回一个新的类型对象。这本质上是类语句的一种动态形式。名称字符串是类名,并成为名称属性;基元组分组化基类,并成为基属性;而dict字典是包含类主体定义的命名空间,并成为dict属性。
所以类型名是'Enum‘,没有基类。
enum
函数有一个**enums
参数,它接受所有命名的参数并将它们放入字典对象中。
在您的例子中,enums
变量是
{
'APP_EXIT': 0,
'CUSTOMER_DEPOSIT': 1,
'CUSTOMER_WITHDRAWAL': 2,
}
这些属性成为返回类型的属性。
Enum
已经添加到Python3.4中,后座被添加到2.4+中。(另见我如何用Python表示'Enum‘?)。
https://stackoverflow.com/questions/22277318
复制