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.