简体   繁体   English

如何挑选一个继承自collections.deque的类?

[英]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. 示例很清楚,我有一个继承到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)
>>> 

The final question, how to serialize this object? 最后一个问题,如何序列化这个对象?

Deque is initialized with up to 3 args : Deque 初始化最多3个args

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

While unpickling, all three (including self) are provided, while your __init__ do not accept them. 在进行unpickling时,会提供所有三个(包括self),而__init__则不接受它们。 Change for example to 例如更改为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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