我可以将变量标记为临时变量,以免被腌制吗?

我可以将变量标记为临时变量,以免被腌制吗?

问题描述:

让我说一堂课

class Thing(object):
    cachedBar = None

    def __init__(self, foo):
        self.foo = foo

    def bar(self):
        if not self.cachedBar:
            self.cachedBar = doSomeIntenseCalculation()
        return self.cachedBar

要进行大量计算,所以我将其缓存在内存中以加快速度.

To get bar some intense calculation, so I cache it in memory to speed things up.

但是,当我腌制这些类之一时,我不想腌制cachedBar.

However, when I pickle one of these classes I don't want cachedBar to be pickled.

我可以将cachedBar标记为易失性/瞬态/不可腌吗?

根据 Pickle文档,您可以提供一种名为__getstate__()的方法,该方法返回代表您要腌制的状态的内容(如果未提供,则pickle使用thing.__dict__).因此,您可以执行以下操作:

According to the Pickle documentation, you can provide a method called __getstate__(), which returns something representing the state you want to have pickled (if it isn't provided, pickle uses thing.__dict__). So, you can do something like this:

class Thing:
      def __getstate__(self):
            state = dict(self.__dict__)
            del state['cachedBar']
            return state

这不一定要是字典,但是如果还有其他要求,则还需要实现__setstate__(state).

This doesn't have to be a dict, but if it is something else, you need to also implement __setstate__(state).