酸洗和取消动态生成的类

我有一个函数返回一个自定义的类类型,然后我想泡菜和unpickle。 我试图按照这个答案和__reduce__文档。 我正在使用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)

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

链接地址: http://www.djcxy.com/p/64829.html

上一篇: Pickling and Unpickling a dynamically generated class

下一篇: Customize pickle behavior for backwards compatibility