Python:Pickle 派生类,就好像它们是基类的实例一样
我想定义一个基类,以便在对派生类实例进行腌制时,将它们像基类的实例一样进行腌制。这是因为派生类可能存在于酸洗的客户端,但不存在于服务器端,但这对服务器来说并不重要,因为它只需要来自基类的信息。我不想为每个客户端动态创建类。
基类只是一个“对象句柄”,其中包含一个 ID,以及在服务器上定义的方法,但我希望客户端能够对服务器类进行子类化并定义新方法(只有客户端才能看到,但这并不重要)。
I want to define a base class so that when derived class instances are pickled, they are pickled as if they are instances of the base class. This is because the derived classes may exist on the client side of the pickling but not on the server side, but this is not important to the server since it only needs information from the base class. I don't want to have to dynamically create classes for every client.
The base class is simply an "object handle" which contains an ID, with methods defined on the server, but I would like the client to be able to subclass the server classes and define new methods (which would only be seen by the client, but that doesn't matter).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信你可以通过给对象一个
__reduce__
方法来做到这一点,返回一个元组,其第一部分应该是BaseClass.__new__
(这将在 unpickle 中加载对象时调用)。请参阅 pickle 文档 (Python 2,< a href="http://docs.python.org/py3k/library/pickle#pickling-class-instances" rel="nofollow">Python 3)了解完整详细信息。我没有尝试过这个。根据您正在执行的操作,使用更简单的序列化格式(例如 JSON)可能会更容易,并且在每一侧都有代码来重建相关对象。
I believe you can do it by giving the object a
__reduce__
method, returning a tuple, the first part of which should beBaseClass.__new__
(this will be called when loading the object in unpickling). See the pickle documentation (Python 2, Python 3) for the full details. I haven't attempted this.Depending on what you're doing, it might be easier to use a simpler serialisation format like JSON, and have code on each side to reconstruct the relevant objects.
您可以在 Python 中动态更改对象的类:
但是,我不确定使用它是否是最佳设计决策。我喜欢Thomas K 使用 JSON 的想法。
You can change an object's class dynamically in Python:
I'm not sure using this is the best design decision, however. I like Thomas K's idea of using JSON.