如何完全在Python中保存/读取类 [英] how to save/read class wholly in Python

查看:135
本文介绍了如何完全在Python中保存/读取类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  som = SOM_CLASS()#包括许多大的困难的数据结构
som.hard_work()
som.save_to_disk(filename)
#或其他程序
som = SOM_CLASS()
som.read_from_file(filename)
som.do_anythink_else()

  som = SOM_CLASS()
save $ b#...
load(som)
som.work()



<

你可以使用来序列化 /docs.python.org/library/pickle.htmlrel =nofollow noreferrer> pickle 。它是向后兼容的,即它将支持未来版本中的所有旧协议。

  import pickle 
$ b b som = SOM_CLASS()
fileObject =<任何类文件对象>
pickle.dump(som,fileObject)
#...
som = pickle.load(fileObject)
som.work()
nadiana.com/python-pickle-insecurerel =nofollow noreferrer> pickle可能不安全(这是一篇文章,每个pickle用户应该知道)。



另一个选择是旧模块元帅


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()

or

som = SOM_CLASS()
save(som)
#...
load(som)
som.work()

what is easiest way to do this?

解决方案

You can (de)serialize with pickle. It is backward-compatible, i.e. it will support all old protocols in future versions.

import pickle

som = SOM_CLASS()
fileObject = <any file-like object>
pickle.dump(som, fileObject)
#...
som = pickle.load(fileObject)
som.work()

But mind that if you transfer pickled objects to another computer, make sure the connection cannot be tampered with as pickle might be unsecure (this is an article that every pickle user should know).

Another alternative is the older module marshal.

这篇关于如何完全在Python中保存/读取类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆