简体   繁体   English

Python:如何保存对象状态并重用它

[英]Python : How to save object state and reuse it

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. 我得到了一些有关如何保存对象的示例(Pickle模块),但无法找到如何从保存状态恢复类/方法并进一步进行操作。

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.

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. 当然, doSomeWork毫无意义,但出于示例的原因,请假设此方法是一个Thread,因此您仍然可以通过将对象设置为restoreClassObject.saveCondition = True来与该对象进行交互,以将其保存在下一个迭代步骤中。

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. CPython不具有无堆栈延续性,因此您可能无法序列化整个程序状态并将其存储在文件中。

You'll have to write some kind of layer than serialises your application data and puts it in a file to implement saving. 您必须编写某种类型的层,然后序列化您的应用程序数据并将其放入文件中以实现保存。

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

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