2014-03-27 5 views
1

나는 Collectionss.OrderedDict 표준 클래스의 하위 클래스를 만들었습니다. 나는 aformentionned 오류를 트리거 다음과 같은 최소한의 코드를 얻을 수 collections.OrderedDict의 몸을 좁혀 그런 행동에 대한 이유를 이해하려고 노력OrderedDict 파생 개체를 pickling

Traceback (most recent call last): 
    File "pickle.py", line 29, in <module> 
    print cPickle.load(f) 
TypeError: ('__init__() takes exactly 1 argument (2 given)', <class '__main__.ConfiguratorsDict'>, ([['toto', 20]],)) 

: 나는 다음과 같은 오류를 얻을이 클래스의 객체를 unpickle 할 때 . 여기에 있습니다 :

import cPickle 

class OrderedDict(dict): 
    def __reduce__(self): 
     items = [[k, self[k]] for k in self] 
     inst_dict = vars(self).copy() 
     for k in vars(OrderedDict()): 
      inst_dict.pop(k, None) 
     if inst_dict: 
      return (self.__class__, (items,), inst_dict) 

     return self.__class__, (items,) 

class ConfiguratorsDict(OrderedDict): 

    def __init__(self): 
     OrderedDict.__init__(self) 

     self._myspec = "blabla" 

if __name__ == "__main__": 

    f = open("test.pickle","wb") 
    c = ConfiguratorsDict() 
    c["toto"] = 20 
    cPickle.dump(c,f) 
    f.close()  
    f = open("test.pickle","rb") 
    print cPickle.load(f) 
    f.close() 

이 시점에서, 나는 정말로 거기에 무엇이 잘못 될지 이해하지 못합니다. 내가 피클 메카니즘으로 잘못 이해 한 점이나 OrderedDict와 관련된 문제가 있습니까?

When a tuple is returned, it must be between two and five elements long. Optional elements can either be omitted, or None can be provided as their value. The contents of this tuple are pickled as normal and used to reconstruct the object at unpickling time. The semantics of each element are:

  • A callable object that will be called to create the initial version of the object. The next element of the tuple will provide arguments for this callable, and later elements provide additional state information that will subsequently be used to fully reconstruct the pickled data.

당신은 호출로하고 두 번째 요소로 클래스를 반환하는 items은 따라서 unpickle입니다 : 당신은 신중하게 충분히 __reduce__ 설명서를 읽어 보지 않았

답변

3

당신의 도움을 위해 많은

감사 items을 클래스에 전달하려고 시도하여 __init__을 호출하지만 __init__은 인수를 취하지 않으므로 오류가 발생합니다.

__init__을 변경하여 인수를 허용하거나 두 번째 요소로 입력하지 않도록하고 빈 터플을 추가해야합니다.

+1

많이 감사합니다! 진실하기 위해서, 나는이 부분을 여러 번 읽었지만 그것을 정말로 이해하지는 못했다. 당신의 대답으로 이제는 분명히 명확 해집니다. – Eurydice

관련 문제