Python: Pickle derived classes as if they were an instance of a base class

I want to define a base class so that when derived instances of classes are pickled, they are pickled as if they were instances of a base class. This is because derived classes can exist on the client side of the etching, but not on the server side, but this is not important for the server, since it only needs information from the base class. I do not want to dynamically create classes for each client.

The base class is just an “object descriptor” that contains the identifier, 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 only the client will see, but that doesn't matter).

+5
source share
2 answers

I believe that you can do this by providing the object with a method __reduce__, returning a tuple, the first part of which should be BaseClass.__new__(this will be called when the object is loaded when unpacking). See the brine documentation ( Python 2 , Python 3 ) for full details. I have not tried to do this.

Depending on what you are doing, it may be easier to use a simpler serialization format, such as JSON, and have code on each side to restore the corresponding objects.

+2
source

The dynamic dynamic class of objects can be changed in Python:

import cPickle as pickle

class Foo(object):
    def __init__(self):
        self.id=1
class Bar(Foo):
    def derived_class_method(self): pass

bar=Bar()
bar.id=2
bar.__class__=Foo                # changes `bar` class to Foo
bar_pickled=pickle.dumps(bar)
bar2=pickle.loads(bar_pickled)
bar.__class__=Bar                # reset `bar` class to Bar
print(repr(bar2))
# <__main__.Foo object at 0xb76b08ec>
print(bar2.id)
# 2

, . . JSON.

0

All Articles