我已经使用了一段时间 - 我无法回忆起我发现它的位置:
#####
# 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)
它是如何工作的?
答案 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)。