腌制动态生成的类? [英] Pickling dynamically generated classes?

查看:87
本文介绍了腌制动态生成的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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

这篇关于腌制动态生成的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆