我正在尝试腌制我定义的(新型)类的对象。但我收到以下错误:
>>> with open('temp/connection.pickle','w') as f:
... pickle.dump(c,f)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/lib/python2.5/pickle.py", line 1362, in dump
Pickler(file, protocol).dump(obj)
File "/usr/lib/python2.5/pickle.py", line 224, in dump
self.save(obj)
File "/usr/lib/python2.5/pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "/usr/lib/python2.5/pickle.py", line 419, in save_reduce
save(state)
File "/usr/lib/python2.5/pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "/usr/lib/python2.5/pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
File "/usr/lib/python2.5/pickle.py", line 663, in _batch_setitems
save(v)
File "/usr/lib/python2.5/pickle.py", line 306, in save
rv = reduce(self.proto)
File "/usr/lib/python2.5/copy_reg.py", line 76, in _reduce_ex
raise TypeError("a class that defines __slots__ without "
TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled
我没有__slots__
在课堂上明确定义。我所做的事情是否隐含地定义了它?我该如何解决这个问题?我需要定义__getstate__
吗?
更新: gnibbler选择了一个很好的例子。我试图腌制的对象的类包装了一个套接字。(我现在想到)套接字定义__slots__
并没有__getstate__
充分的理由。我假设一旦一个进程结束,另一个进程就不能解开并使用前一个进程的套接字连接。因此,虽然我接受了Alex Martelli的出色回答,但我将不得不采取与酸洗不同的策略来“共享”对象引用。