Pickling and Unpickling a dynamically generated class
I have a function that returns a customized class type which I then want to pickle and unpickle. I am trying to follow this answer and the __reduce__
documentation. I am using Python 2.7. The difference from that answer is that my function accepts an arbitrary class and returns a class derived from it. This is what I have:
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
The dumps
command works but the loads
command raises a 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)
How can I overcome this? If this problem stems from a basic design flaw, how would I restructure this code to enable serialization of instances of dynamically generated classes?
链接地址: http://www.djcxy.com/p/64830.html上一篇: Python 3.6酸洗自定义程序
下一篇: 酸洗和取消动态生成的类