示例很清楚,我有一个继承deque的类和一个模块'collections'的方法,有时候我使用defaultdict,有些则没有。
>>> from collections import deque, defaultdict
>>> import pickle
>>> class lista(deque):
... def __init__(self):
... deque.__init__(self)
... self.lib = defaultdict(dict)
...
>>> p = lista()
>>> p.append("a")
>>> p.append("b")
>>> p.lib['t']=0
>>> p.__reduce__()
(<class '__main__.lista'>, (['a', 'b'], None), {'lib': defaultdict(<type 'dict'>, {'t': 0})})
>>> pik = pickle.dumps(p)
>>> unpik = pickle.loads(pik)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1382, in loads
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 858, in load
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1133, in load_reduce
TypeError: __init__() takes exactly 1 argument (3 given)
>>>
最后一个问题,如何序列化这个对象?
答案 0 :(得分:4)
Deque是initialized with up to 3 args:
class collections.deque([iterable[, maxlen]])
虽然提供了unpickling,但提供了所有三个(包括self),而__init__
则不接受它们。
例如更改为
class lista(deque):
def __init__(self, iterable=(), maxlen=None):
deque.__init__(self, iterable, maxlen)
self.lib = defaultdict(dict)