简体   繁体   English

如何有选择地腌制类实例的变量?

[英]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.

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