我正在使用 type()动态生成最终将被腌制的类。问题在于,非腌制过程需要类的定义才能重新构造已腌制的对象。
I'm using type() to dynamically generate classes that will ultimately be pickled. The problem is that the un-pickling process needs the definition of the class in order to re-construct the object that has been pickled.
这就是我遇到的问题。我不知道如何以某种方式提供取消选择程序的方法,以便从动态生成的类生成实例。
This is where I'm stuck. I don't know how to somehow provide the unpickler a way to generate an instance from a class that was dynamically generated.
任何提示都值得赞赏
谢谢!
以下是问题的一个示例:
Here's an example of the problem:
>>> class Foo(object): ... pass >>> g=type('Goo',(Foo,),{'run':lambda self,x: 2*x } )() >>> cPickle.dumps(g) PicklingError: Can't pickle <class '__main__.Goo'>: attribute lookup __main__.Goo failed这显然是有效的,但仅适用于可腌制基类(具有可查找模块的定义)创建的动态类:
This evidently works, but only from dynamic classes created from a pickle-able base class (with find-able module definition):
import cPickle class Foo(object): pass def dynamic(): return type('Goo',(Foo,),{'run':lambda self,x: 2*x } )() g=type('Goo',(Foo,),{'run':lambda self,x: 2*x , '__reduce__': lambda self: (dynamic,tuple()) } )() gg=cPickle.loads ( cPickle.dumps(g) ) print gg.run(10)推荐答案
何时Pickler遇到一个不知道类型的对象,它会寻找减少方法。在使用类型构建自定义类时定义此方法应该可以解决酸洗的问题。
When the Pickler encounters an object of a type it knows nothing about, it looks for a reduce method. Defining this method when you build your custom class using type should solve the problem of pickling.
如果提供初始args,则可能还需要定义 getnewargs方法
If you provide initial args then in addition you might need to define a getnewargs method
更多推荐
腌制动态生成的类?
发布评论