Program Club

자신을 피클하는 방법?

proclub 2021. 1. 8. 20:48
반응형

자신을 피클하는 방법?


내 클래스가 단순히 클래스의 피클을 수행하는 저장 및로드 함수를 구현하기를 원합니다. 그러나 분명히 아래와 같은 방식으로 'self'를 사용할 수 없습니다. 어떻게 할 수 있습니까?

self = cPickle.load(f)

cPickle.dump(self,f,2)

이것이 내가 한 일입니다. 업데이트는 __dict__클래스에 추가 한 새 멤버 변수를 유지하고 객체가 마지막으로 피클되었을 때 있던 변수 만 업데이트한다는 것을 의미합니다. 클래스 자체 내에서 코드 저장 및로드를 유지하면서 가장 간단 해 보이므로 코드를 호출하면 object.save ()가 수행됩니다.

def load(self):
    f = open(self.filename, 'rb')
    tmp_dict = cPickle.load(f)
    f.close()          

    self.__dict__.update(tmp_dict) 


def save(self):
    f = open(self.filename, 'wb')
    cPickle.dump(self.__dict__, f, 2)
    f.close()

덤프 부분은 제안한대로 작동해야합니다. 로딩 부분 의 경우 주어진 파일에서 인스턴스를로드하고 반환 하는 @classmethod정의 할 수 있습니다 .

@classmethod
def loader(cls,f):
    return cPickle.load(f)

호출자는 다음과 같은 작업을 수행합니다.

class_instance = ClassName.loader(f)

저장된 피클에서 수업 자체를 업데이트하려면 ... __dict__.update자신의 답변에서와 같이 를 사용해야 합니다. 그것은 마치 고양이가 꼬리를 쫓는 것과 비슷하지만 ... 인스턴스가 본질적으로 이전 상태로 스스로를 "재설정"하도록 요청하는 것과 같습니다.

답변에 약간의 조정이 있습니다. 실제로 피클 할 수 있습니다 self.

>>> import dill
>>> class Thing(object):
...   def save(self):
...     return dill.dumps(self)
...   def load(self, obj):
...     self.__dict__.update(dill.loads(obj).__dict__)
... 
>>> t = Thing()
>>> t.x = 1
>>> _t = t.save()
>>> t.x = 2
>>> t.x
2
>>> t.load(_t)
>>> t.x
1

내가 사용 loads하고 dumps대신 load하고 dump내가 원하는 때문에 피클 문자열로 저장합니다. loaddump파일을 사용 하는 것도 작동합니다. 그리고 실제로 dill클래스가 대화 형으로 정의 된 경우에도 나중에 사용하기 위해 클래스 인스턴스를 파일로 피클하는 데 사용할 수 있습니다 . 위에서 계속 ...

>>> with open('self.pik', 'w') as f:
...   dill.dump(t, f)
... 
>>> 

그런 다음 중지하고 다시 시작합니다 ...

Python 2.7.10 (default, May 25 2015, 13:16:30) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> with open('self.pik', 'r') as f:
...   t = dill.load(f)
... 
>>> t.x
1
>>> print dill.source.getsource(t.__class__)
class Thing(object):
  def save(self):
    return dill.dumps(self)
  def load(self, obj):
    self.__dict__.update(dill.loads(obj).__dict__)

>>> 

I'm using dill, which is available here: https://github.com/uqfoundation


There is an example of how to pickle an instance here, in the docs. (Search down for the "TextReader" example). The idea is to define __getstate__ and __setstate__ methods, which allow you to define what data needs to be pickled, and how to use that data to re-instantiate the object.


How about writing a class called Serializable that would implement dump and load and make your class inherit from it?

ReferenceURL : https://stackoverflow.com/questions/2709800/how-to-pickle-yourself

반응형