当我尝试去除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。
答案 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
本身添加所需的功能。