我可以将变量标记为瞬态,这样它们就不会被腌制吗?
假设我有一堂课:
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
为了进行一些密集的计算,所以我将其缓存在内存中以加快速度。
但是,当我腌制这些类之一时,我不希望 cachedBar
被腌制。
我可以将cachedBar标记为易失性/瞬态/不可picklable吗?
Let's say I have a class:
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.
However, when I pickle one of these classes I don't want cachedBar
to be pickled.
Can I mark cachedBar as volatile / transient / not picklable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 Pickle 文档,您可以提供一个名为
__getstate__() 的方法
,它返回代表您想要腌制的状态的内容(如果未提供,pickle
使用thing.__dict__
)。所以,你可以这样做:这不一定是一个字典,但如果它是其他东西,你还需要实现
__setstate__(state)
。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
usesthing.__dict__
). So, you can do something like this:This doesn't have to be a dict, but if it is something else, you need to also implement
__setstate__(state)
.实现
__getstate__
仅返回以下部分要腌制的对象Implement
__getstate__
to return only what parts of an object to be pickled