Pickling and Unpickling动态生成的类

时间:2018-02-08 10:30:43

标签: python class pickle factory

我有一个函数返回一个自定义类类型,然后我想要pickle和unpickle。我正在尝试关注this answer__reduce__ documentation。我使用的是Python 2.7。 与答案的不同之处在于我的函数接受一个任意类并返回一个派生自它的类。这就是我所拥有的:

class Base(object):
    def foo(self, a):
        return a + 1

    def __reduce__(self):
        return _InitializeDynamicClass(), (), self.__dict__


def get_dynamic_class(BaseClass):  # BaseClass can be any class derived from Base, or Base itself
    class DynamicClass(BaseClass):
        def foo(self, a):
            return BaseClass.foo(self, a) + 2
    return DynamicClass


class _InitializeDynamicClass(object):
    def __call__(self, param_value):
        obj = _InitializeDynamicClass()
        obj.__class__ = get_dynamic_class(Base)  # giving Base here is probably wrong, but how can I fix it?
        return obj


if __name__ == "__main__":
    from pickle import dumps, loads

    dynamic_instance = get_dynamic_class(Base)()
    dynamic_instance_dump = dumps(dynamic_instance)
    del dynamic_instance
    dynamic_instance = loads(dynamic_instance_dump)  # raises TypeError

dumps命令有效但loads命令引发TypeError

  File "/home/user/anaconda2/lib/python2.7/pickle.py", line 1388, in loads
    return Unpickler(file).load()
  File "/home/user/anaconda2/lib/python2.7/pickle.py", line 864, in load
    dispatch[key](self)
  File "/home/user/anaconda2/lib/python2.7/pickle.py", line 1139, in load_reduce
    value = func(*args)
TypeError: __call__() takes exactly 2 arguments (1 given)

我怎样才能克服这一点?如果这个问题源于一个基本的设计缺陷,我将如何重构此代码以启用动态生成的类的实例的序列化?

0 个答案:

没有答案