腌制动态生成的类?

编程入门 行业动态 更新时间:2024-10-26 09:34:27
本文介绍了腌制动态生成的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

腌制动态生成的类?

本文发布于:2023-06-06 05:53:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/534730.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!