简体   繁体   中英

How to pickle an class that inherits from collections.deque?

The example is clear, I have a class that inherits to deque and a method of the module 'collections', sometimes I use defaultdict, others do not.

>>> 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)
>>> 

The final question, how to serialize this object?

Deque is initialized with up to 3 args :

class collections.deque([iterable[, maxlen]])

While unpickling, all three (including self) are provided, while your __init__ do not accept them. Change for example to

class lista(deque):
    def __init__(self, iterable=(), maxlen=None):
        deque.__init__(self, iterable, maxlen)
        self.lib = defaultdict(dict)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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