[英]How to pickle a class instance's variables selectively?
I have a class instance: 我有一个类实例:
class A:
def __init__(self,shape):
self.shape = shape
self.matrix = numpy.zeros(shape)
I did some multiplication on self.matrix
. 我对
self.matrix
做了一些乘法。 When I am pickling the instance of class A
, I don't want to pickle self.matrix
for some reason. 当我腌制
A
类的实例时,由于某种原因,我不想腌制self.matrix
。
Currently, my solution is to set self.matrix = None
before pickle and reset self.matrix
to zeros(shape)
after loading from pickled file. 目前,我的解决方案是在腌制之前将
self.matrix = None
设置为self.matrix = None
,并在从腌制文件中加载self.matrix
重置zeros(shape)
。
Is there a more elegant solution? 有没有更优雅的解决方案? Like the
transient
keyword in Java. 就像Java中的
transient
关键字一样。
Use the hook methods to limit what is pickled and what is unpickled. 使用钩子方法可以限制腌制和未腌制的物质。
Here, you could use a __getstate__
with corresponding __setstate__
method: 在这里,您可以使用
__getstate__
和相应的__setstate__
方法:
class A:
def __init__(self, shape):
self.shape = shape
self.matrix = numpy.zeros(shape)
def __getstate__(self):
return (self.shape,)
def __setstate__(self, state):
self.shape, = state
self.matrix = numpy.zeros(self.shape)
The __setstate__
could be simplified to: 可以将
__setstate__
简化为:
def __setstate__(self, state):
self.__init__(*state)
if your __init__
is reusable in this manner. 如果您的
__init__
以这种方式可重复使用。 In that case you can also use __getinitargs__
instead of __getstate__
and drop the __setstate__
altogether: 在这种情况下,您也可以使用
__getinitargs__
代替__getstate__
并将__setstate__
:
class A:
def __init__(self, shape):
self.shape = shape
self.matrix = numpy.zeros(shape)
def __getinitargs__(self):
return (self.shape,)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.