how to save/read class wholly in Python
1 2 3 4 5 6 7 | som = SOM_CLASS() # includes many big difficult data structures som.hard_work() som.save_to_disk(filename) #then later or another program som = SOM_CLASS() som.read_from_file(filename) som.do_anythink_else() |
或
1 2 3 4 5 | som = SOM_CLASS() save(som) #... load(som) som.work() |
最简单的方法是什么?
你可以用pickle反序列化。它是向后兼容的,也就是说,它将在未来的版本中支持所有旧的协议。
1 2 3 4 5 6 7 8 | import pickle som = SOM_CLASS() fileObject = pickle.dump(som, fileObject) #... som = pickle.load(fileObject) som.work() |
但是请注意,如果您将已腌制的对象传输到另一台计算机,请确保连接不会被篡改,因为腌制可能不安全(这是每个腌制用户都应该知道的一篇文章)。
另一种选择是旧的模块封送。
看看python的
我使用此代码:
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 | 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) |
此代码保存类并从其实际的类实例名称加载该类。代码来自我的博客http://www.schurpf.com/python-save-a-class/。