我有一个嵌套类:
class WidgetType(object): class FloatType(object): pass class TextType(object): pass
。。以及引用嵌套类类型(不是其实例)的项目
class ObjectToPickle(object): def __init__(self): self.type = WidgetType.TextType
尝试序列化ObjectToPickle类的实例会导致:
PicklingError: Can't pickle <class 'setmanager.app.site.widget_data_types.TextType'>
有没有办法在python中pickle嵌套类?
我知道这是一个非常古老的问题,但是我从来没有看到过对这个问题的满意的解决方案,除了对代码进行重新构造的明显且最有可能是正确的答案。
不幸的是,这样做并不总是可行的,在这种情况下,作为最后的手段,可以对在另一个类中定义的类的实例进行pickle操作。
^{} function 的python文档声明您可以返回
因此,您只需要一个对象,它可以返回适当类的实例。这个类必须本身是可选择的(因此,必须存在于
__main__
级别),并且可以简单到:因此,剩下的就是在FloatType上的
__reduce__
方法中返回适当的参数:结果是一个嵌套的类,但可以对实例进行pickle(需要进一步的工作来转储/加载
__state__
信息,但根据__reduce__
文档,这相对简单)。同样的技术(稍加代码修改)可以应用于深度嵌套的类。
一个充分发挥作用的例子:
我最后要说的是记住其他答案的意思:
pickle模块正在尝试从该模块获取TextType类。但是由于类是嵌套的,所以它不起作用。贾森的建议会奏效的。 下面是pickle.py中负责错误消息的行:
klass = getattr(mod, name)
当然在嵌套类情况下不起作用。要演示正在进行的操作,请在选取实例之前尝试添加这些行:此代码将TextType作为属性添加到模块中。腌制应该很好。不过,我不建议你用这种方法。
如果您使用
dill
而不是pickle
,它就会工作。把莳萝拿到这里:https://github.com/uqfoundation/dill
相关问题 更多 >
编程相关推荐