1

I created an instance like this:

class some_class():
    def __init__(self, aa, bb):
        self.a = aa
        self.b = bb

    def add(self):
        self.c = self.a + self.b
        return self.c


instance001 = some_class(2,200)

And now I try to save instance001 to hard drive for future use.

with open('Storage', 'w') as file:
    file.write(instance001)

This doesn't work. How To store instances?

Preferred format would be hdf, but any other idea is welcome.

NOTE: Pandas in in heavy use.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
Ranny
  • 315
  • 2
  • 13

1 Answers1

2

In case of pure Python classes you can simply use pickle:

import pickle
with open('Storage', 'wb') as f:
    pickle.dump(instance001, f)

and load it:

with open('Storage', 'rb') as f:
    instance002 = pickle.load(f)

print(instance002.a)   # 2
print(instance002.b)   # 200
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • It works. I figured it out myself too : ) Now I have to learn if I can append objects to pickle as I have many instances to save. Thanks – Ranny Jul 15 '17 at 14:10
  • @Ranny You can always pickle a list/tuple/dict containing several instances. – MSeifert Jul 15 '17 at 14:11
  • I did it with a list. Can I save class definition in it as well to pass it to another script? – Ranny Jul 15 '17 at 14:19
  • @Ranny That's probably better solved using `imports`. But if that isn't feasible I think it would be better to ask a **new** question. That's too hard to answer in the comments. – MSeifert Jul 15 '17 at 14:24
  • @Ranny I suggest you read the official pickle docs. There's a lot of info in there, so you will need to read them several times, just skim them the first time through to get a general overview. And do some small experiments to see how it all works. You can pickle many things, and some objects that pickle can't handle by itself can be given some extra methods so that pickle knows how to handle them. – PM 2Ring Jul 15 '17 at 14:30
  • Yes. Problem in another q: https://stackoverflow.com/questions/45046636/calling-pandas-from-within-class (I can edit picle and change values there - cool) Thanks. – Ranny Jul 15 '17 at 14:31