如何在Python中完全保存/读取类
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()
或者
som = SOM_CLASS()
save(som)
#...
load(som)
som.work()
什么是最简单的方法来做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 pickle 进行序列化(反序列化)。它是向后兼容的,即它将在未来版本中支持所有旧协议。
但请注意,如果您将 pickle 对象传输到另一台计算机,请确保连接不会被篡改,因为 pickle 可能不安全(这是每个pickle用户都应该知道的文章)。
另一种选择是旧模块 marshal。
You can (de)serialize with pickle. It is backward-compatible, i.e. it will support all old protocols in future versions.
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.
我使用此代码:
此代码从其实际的类实例名称保存和加载该类。代码来自我的博客 http://www.schurpf.com/python-save-a -类/。
I use this code:
This code saves and loads the class from its actual class instance name. Code is from my blog http://www.schurpf.com/python-save-a-class/.
看一下 Python 的
pickle
库。Take a look at Python's
pickle
library.以这种方式使用
pickle
:Use
pickle
in this way: