Let me share a little code snippet I use at times which I call “python save a class”. I came up with a very simple and easy way to do that. Check out my code snippet below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<pre lang="py" toggle="no">import cPickle
import traceback
class someClass():
def __init__(self):
#set name from variable name. http://stackoverflow.com/questions/1690400/getting-an-instance-name-inside-class-init
(filename,line_number,function_name,text)=traceback.extract_stack()[-2]
def_name = text[:text.find('=')].strip()
self.name = def_name
try:
self.load()
except:
##############
#to demonstrate
self.someAttribute = 'bla'
self.someAttribute2 = ['more']
##############
self.save()
def save(self):
"""save class as self.name.txt"""
file = open(self.name+'.txt','w')
file.write(cPickle.dumps(self.__dict__))
file.close()
def load(self):
"""try load self.name.txt"""
file = open(self.name+'.txt','r')
dataPickle = file.read()
file.close()
self.__dict__ = cPickle.loads(dataPickle)
def __str__(self):
return str(self.__dict__)
The class is saved as whatever the name of the class instance is. Please not that this works with all datatypes that Pickle supports.
Example
1
<pre parse="no" toggle="no">myClass = someClass()
Will try to load a saved class called “myClass.txt” otherwise set some sample values and save the class. Feel free to use this code.
Credits
I would also like to give credit to StackOverflow – Getting an instance name inside class init which showed the cool little trick of how to getting the class instance name.
I hope I was able to show you how to save a class in python. Let me know if you have any questions or comments.