Can cPickle save reshaped numpy object reference?
<p>I have a class defined as:</p>

<pre><code>class A():
    def __init__():
        self.a = np.array([0,1,2,3,4,5])
        self.b = self.a.reshape((2, 3))
</code></pre>

<p>now, b is in fact a reshaped reference of array a. If we change the first element of a:<code>a[0] = 10</code>, <code>b[0, 0]</code> will also change to 10.
I use cPickle to save this array, however, when I load the dump. a and b become different array. I want to know whether there are any method to make b still the reference of a?</p>

<p>You can use <code>__getstate__</code> and <code>__setstate__</code> to control the pickle:</p>

<pre><code>import numpy as np

class A:
    def __init__(self):
        self.a = np.array([0,1,2,3,4,5])
        self.b = self.a.reshape((2, 3))

    def __getstate__(self):
        return {"a":self.a, "b":self.b.shape}

    def __setstate__(self, state):
        self.a = state["a"]
        self.b = self.a.reshape(state["b"])

import pickle

x = A()
s = pickle.dumps(x)
y = pickle.loads(s)

y.b.base is y.a
</code></pre>

python numpy pickle