0

hello I'm having trouble understanding how to save and load a class instance. I have seen this question about __setstate__ and __getstate__ but it didnøt help much.

Let's say I have a class:

class Foo(object):
    def __init__(self, a, b):
        super(Foo, self).__init__()
        self.a = a
        self.b = b
        self.c = 0

    def Sum(self):
        self.c = self.a + self.b

such that:

foo = Foo(1, 1)
print('c is defaulted to 0')
print(foo.c)
foo.Sum()
print('Now it is the sum')
print(foo.c)

will print:

c is defaulted to 0
0
Now it is the sum
2

What I want to do is write a method Save and a method Load to save and load this class instance. so that:

foo = Foo(1, 1)
print('c is defaulted to 0')
print(foo.c)
foo.Sum()
print('Now it is the sum')
print(foo.c)
foo.Save(filename)
foo.a = 0
foo.Sum()
print('Changed c')
print(foo.c)
foo.Load(filename)
print('Reloaded class')
print(foo.c)

should output:

c is defaulted to 0
0
Now it is the sum
2
Changed c
1
Reloaded class
2

At the moment I have written the methods as such:

def Save(self, file):
    f = open(file, "wb")
    pickle.dump(self, f)
    f.close()
def Load(self, file):
    f = open(file, "rb")
    self = pickle.load(f)
    f.close()

However this doesn't work as value of foo.c is still at 1. I am clearly making some mistake in understanding how the class instance is saved but I can't understand why. Thanks for the help.

mmonti
  • 71
  • 11
  • `self` is just a local variable - assigning a new value to it has absolutely no effect outside of the function. Normally, something like your `Load()` would be a class or static method, that *returns* the loaded object. If you really want it to be a method of an existing instance, then you would need to explicitly copy all of the attributes from the unpickled instance into the existing one. – jasonharper Oct 29 '20 at 15:18
  • mmm I see, it doesn't have to be. This means that I have to call the Load() function and assign it back to foo, if I want it to change. To be clear, if I want to update the class attributes of a class that is already instantiated from a saved state I have to do it manually? – mmonti Oct 29 '20 at 15:28

0 Answers0