Python : How to save object state and reuse it

天涯浪子 提交于 2019-12-24 12:46:56

问题


I want to save object state and reuse it after some time. I got some example on How to save object (Pickle module), I was not able to find how to resume class/method from the save state and proceed further.

Like game, we can save the game and latter we can continue, I know in game we save all the data and game read the data and build the game.

I want to save complete object and when I restore it it start working from saved state.

For example

class Test(objet):
   def doSomeWork(self):
     index = 0
     while index < 99999:
        print index 
        index  += 1
        if saveCondition:
          # suppose when condition become True index value is 100
          saveCondition = None
          saveTheObjectToFile() # this might be saved in file
restoreClassObject = getSavedObject() # get object from file
# Now this should start printing from 100
# I want to resume the object state when it was saved.

回答1:


The easiest way is to make sure that the state of the Object is not saved in local scopes, but as attributes of the object. Consider

import cPickle

class Test(objet):
    def __init__(self, filename="mystate.pickle"):
        self.index = 0
        self.filename = filename

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

    def doSomeWork(self):
        while self.index < 99999:
            print self.index 
            self.index  += 1
            if self.saveCondition:
              # suppose when condition become True index value is 100
              self.saveCondition = False
              self.save() # this might be saved in file

restoreClassObject = getSavedObject() # get object from file

Of course doSomeWork makes no sense as such, but for the sake of the example imagine this method was a Thread so you could still interact with the object by setting it's restoreClassObject.saveCondition = True to save it in the next iteration step.




回答2:


CPython doesn't have the kind of continuations that stackless has so you might not be able to serialise the entire program state and store it in a file.

You'll have to write some kind of layer than serialises your application data and puts it in a file to implement saving.



来源:https://stackoverflow.com/questions/5673127/python-how-to-save-object-state-and-reuse-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!