是否可以在枚举类型中添加名为"None"的值?

geo*_*rew 7 python enums

我可以在枚举中添加名为"无"的值吗?例如

from enum import Enum
class Color(Enum):
    None=0 #represent no color at all
    red = 1
    green = 2
    blue = 3

color=Color.None

if (color==Color.None):
    #don't fill the rect
else:
    #fill the rect with the color
Run Code Online (Sandbox Code Playgroud)

这个问题与我之前的问题有关 如何设置变量的子属性?

当然,我理解上面None的内容enum不起作用.但是从供应商的代码中,我确实看到了这样的东西: bird.eye.Color=bird.eye.Color.enum.None 我检查过type(bird.eye.Color) 它是一个<class 'flufl.enum._enum.IntEnumValue'> 如此flufl.enum用的.我想使用a flufl.enum或a 不应该有很大的不同Enum.非常感谢!

Bre*_*bel 5

您可以使用Enum构造函数而不是创建子类来执行此操作

>>> from enum import Enum
>>> 
>>> Color = Enum('Color', {'None': 0, 'Red': 1, 'Green': 2, 'Blue': 3})
>>> Color.None
<Color.None: 0
Run Code Online (Sandbox Code Playgroud)

编辑:这使用enum34python 2的backport 工作。在 python 3 中,您将能够Enum使用None属性创建,但您将无法使用点表示法访问。

>>> Color.None
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

奇怪的是,你仍然可以访问它 getattr

>>> getattr(Color, 'None')
<Color.None: 0>
Run Code Online (Sandbox Code Playgroud)