如何在Python中挑选复杂的枚举值

时间:2017-05-03 09:13:35

标签: python enums pickle

当我尝试去除pickle复杂的枚举实例时,我总是得到“ValueError:BLUE不是有效的颜色”。

有什么方法可以腌制和去除斑点吗?

from pickle import loads, dumps
from enum import Enum


class ColorType(object):

    def __init__(self, counter, name):
        self.counter = counter
        self.name = name

    def __str__(self):
        return self.name


class Colors(Enum):
    GREEN = ColorType(1, 'GREEN')
    BLUE = ColorType(2, 'BLUE')


color = Colors.BLUE
print(color is loads(dumps(color)))

我正在使用Python 2.7。

2 个答案:

答案 0 :(得分:2)

不要使用自定义类作为枚举值;这里没有必要。您的具体示例根本不需要单独的类,您可以使用:

class Colors(Enum):
    GREEN = 1
    BLUE = 2

    def __str__(self):
        return self.name

    @property
    def counter(self):
        return self.value

这有更好的 str().counter行为;您的代码需要将str()应用于Color.<name>.value,而不是直接应用于Color.<name>

对于其他自定义方法和属性,将它们直接放在Enum子类上,它们也将成为枚举成员的一部分。如果每个条目需要更多值,请设置元组并使用__init__方法将该元组拉开。该文档有一个很好的Planet example,可以进一步说明这一点。

演示:

>>> Colors.BLUE
<Colors.BLUE: 2>
>>> Colors.BLUE.value
2
>>> Colors.BLUE.counter
2
>>> str(Colors.BLUE)
'BLUE'
>>> Colors.BLUE is loads(dumps(Colors.BLUE))
True

答案 1 :(得分:1)

这里的问题是基本平等:

start()

因此,当>>> ColorType(2, 'BLUE') == ColorType(2, 'BLUE') False 尝试找到Colors的未标记值的匹配时,它就会失败。

解决方案很简单:将ColorType(2, 'BLUE')__eq__方法添加到`ColorType&#39;:

__ne__

NB 我同意@MartijnPieters,在大多数情况下,您应该只为class ColorType(object): def __init__(self, counter, name): self.counter = counter self.name = name def __str__(self): return self.name def __eq__(self, other): return self.name == other.name and self.counter == other.counter def __ne__(self, other): # not needed in Python 3 return self.name != other .name or self.counter != other.counter 本身添加所需的功能。