gpt4 book ai didi

python - 这个 "enumeration"成语是如何工作的?

转载 作者:太空宇宙 更新时间:2023-11-04 01:19:25 24 4
gpt4 key购买 nike

我已经使用它一段时间了 - 我不记得是在哪里找到它的:

#####
# 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)

它是如何工作的?

最佳答案

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

With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the name attribute; the bases tuple itemizes the base classes and becomes the bases attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the dict attribute.

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

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

在你的例子中,enums 变量是

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

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


仅供引用,Enum已添加到 Python 3.4 和 backported到 2.4+。 (另请参见 How can I represent an 'Enum' in Python?)。

关于python - 这个 "enumeration"成语是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22277318/

24 4 0