Python:保存和加载类定义
我对使用 pickle 模块保存和加载对象感兴趣,您可以在我之前问过的问题中读到: Python:使用 pickle 模块保存和加载对象时出错
有人评论:
1,另一种方式:引发错误是因为 pickle 想要加载 Fruits 类的实例并搜索定义它的类定义,但没有找到它,因此引发了错误
现在我想保存并加载类定义以解决我在前面提到的问题中描述的问题。 太感谢了!
I am interested in saving and load objects using the pickle module as you can read in a question I asked before:
Python: Errors saving and loading objects with pickle module
Someone commment:
1, In an other way: the error is raise because pickle wanted to load an instance of the class Fruits and search for the class definition where it was defined, but it didn't find it so it raise the error
Now I want to save and load a class definition in order to solve the problem I describe in the question mentioned before.
Thank you so much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
pickle 模块保存和加载对象的内部状态。代码不是内部状态的一部分,甚至对于类来说也不是,因此它变得很棘手。
最明显的方法是将整个类定义放在一个字符串中,腌制该字符串,然后加载它,然后 exec() 该字符串。另一个可能有效或无效的选择是拥有一个元类,它也可以对代码进行pickle和unpickle,但这方式更加困难,而且实际上并没有更好。
然而,出于多种原因,这是一个极其糟糕的主意,而且我敢打赌,你没有充分的理由这样做。你有 99.9% 的可能性找错了树。您正在尝试解决遇到的问题,因为您选择了错误的解决方案来做某事,现在您正在尝试解决该解决方案给您带来的问题,而不是选择一个可能非常容易实现的更好的解决方案。
因此,您不仅需要解释当前遇到的问题,还需要解释您试图解决的大规模用例。然后我们可以告诉您如何以更好的方式解决该用例。
The pickle module saves and loads the objects internal state. The code is not a part of the internal state, not even for classes, so therefore it gets tricky.
The obvious way is to make the whole class definition in a string, pickle that string, and then load it, and exec() that string. Another option that may or may not work is to have a metaclass that can pickle and unpickle the code as well, but that is way more difficult, and not really any better.
This is however an extremely bad idea for tons of reasons, and I would bet a significant amount of my reputation point on that you have no good reason to do that. You are with 99.9% likelihood barking up the wrong tree. You are trying to solve a problem you have because you have chosen the wrong solution to do something, and now you are trying to solve the problems that solution is giving you, instead of choosing a better solution that likely will be very simple to implement.
So you need to not only explain the current problem you have, but also the large scale usecase you are trying to solve. We can then tell you how to solve that usecase in a better way.