简体   繁体   English

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

[英]Is it possible to add a value named 'None' to enum type?

can I add a value named 'None' to a enum? 我可以在枚举中添加名为“无”的值吗? for example 例如

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

This question is related to my previous question How to set a variable's subproperty? 这个问题与我之前的问题有关如何设置变量的子属性?

Of course, I understand the above None in enum doesn't work. 当然,我明白上面Noneenum不起作用。 but from the vendor's code, I do see something like this: bird.eye.Color=bird.eye.Color.enum.None I checked the type(bird.eye.Color) it is a <class 'flufl.enum._enum.IntEnumValue'> so a flufl.enum is used. 但是根据供应商的代码,我确实看到类似这样的东西: bird.eye.Color=bird.eye.Color.enum.None我检查了type(bird.eye.Color)它是一个<class 'flufl.enum._enum.IntEnumValue'>所以使用flufl.enum I suppose it should not be very different to use a flufl.enum or a Enum . 我想使用flufl.enumEnum应该没有什么不同。 Thanks a lot! 非常感谢!

You can do this using the Enum constructor rather than creating a subclass 您可以使用Enum构造函数而不是创建子类来完成此操作

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

EDIT: This works using the enum34 backport for python 2. In python 3, you will be able to create the Enum with the None attribute, but you won't be able to access using dot notation. 编辑:这使用enum34 backport for python 2.在python 3中,您将能够使用None属性创建Enum ,但您将无法使用点表示法访问。

>>> Color.None
SyntaxError: invalid syntax

Oddly, you can still access it with getattr 奇怪的是,您仍然可以使用getattr访问它

>>> getattr(Color, 'None')
<Color.None: 0>

You can not do this directly because it is a syntax error to assign to None . 您不能直接执行此操作,因为分配给None是语法错误。

Neither should you set an attribute on your enum class dynamically, because this will interfere with the metaclass logic that Enum uses to prepare your class. 也不应该动态地在枚举类上设置属性,因为这会干扰Enum用来准备类的元类逻辑。

You should just use a lowercase name none to avoid the name collision with python's None singleton. 您应该使用小写名称none来避免名称与python的None单例冲突。 For the use-case you have described, there is no disadvantage to this approach. 对于您所描述的用例,这种方法没有任何缺点。

Not quite the way you tried, but you can do this: 不是你尝试的方式,但你可以这样做:

# After defining the class Color as normal, but excluding the part for None...
setattr(Color, 'None', 0)

color = Color.None
if color == Color.None:
    ...

Note: I did this in Python 2. Not sure if you want this in Python 2 or 3 because you didn't specify, and I don't have a copy of Python 3 installed on this machine to test with. 注意:我在Python 2中执行了此操作。不确定您是否希望在Python 2或3中使用它,因为您没有指定,并且我没有在此计算机上安装Python 3的副本来进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM