具有数字名称的枚举

Enums with numeric names

以下内容在 Python 中不起作用:

class MemorySize(int, Enum):
    "1024" = 1024
    "2048" = 2048

那么最接近的方法是什么,而不必用文字输入整个数字并使其输入安全?

来自 docs:

An enumeration is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over.

因此,枚举成员应该是 symbolic names,而不是字符串文字。

如果你想用数字作为名字,你可以用_m_作为前缀,因为私有属性start with underscore

此外,您还可以使用 IntEnum 进行整数枚举。

from enum import IntEnum


class MemorySize(IntEnum):
    m_1024 = 1024
    m_2048 = 2048

print(MemorySize.m_1024.value)

输出

1024

此外,您可以省略此处的逗号 "1024" = 1024,

实际上 1024, 是一个只有一个元素 (1024, ) 的元组,而 1024 只是一个整数。我只是好奇,为什么你可以将元组和整数传递给枚举属性。

我发现 IntEnum 属性的值传递给了 int 构造函数。在此之前,它将 args 转换为 EnumMeta.__new__

中的元组
if not isinstance(value, tuple):
    args = (value, )
else:
    args = value

您可以传递给 int 构造函数的第二个参数,基数: 因为 int("ff", 16) == 255。或者只使用字符串常量而不是 int 因为 int("123") == 123.

因此,您可以像这样将 IntEnum 值与任何数字系统一起使用(尽管我认为这不是实践中使用它的好方法)

class WeiredEnum(IntEnum):
    m_255 = "ff", 16
    m_256 = "256"

print(WeiredEnum.m_255.value)
print(type(WeiredEnum.m_256.value))
> 255
> <class 'int'>