取消拾取对象时发生AttributeError [英] AttributeError when unpickling an object

查看:90
本文介绍了取消拾取对象时发生AttributeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在一个模块中腌制一个类的实例,然后在另一个模块中对其进行腌制.

I'm trying to pickle an instance of a class in one module, and unpickle it in another.

我在这里腌制

import cPickle

def pickleObject():
    object = Foo()
    savefile = open('path/to/file', 'w')
    cPickle.dump(object, savefile, cPickle.HIGHEST_PROTOCOL)


class Foo(object):
    (...)

这是我尝试解开的地方:

and here's where I try to unpickle:

savefile = open('path/to/file', 'r')
object = cPickle.load(savefile)

在第二行,我得到AttributeError: 'module' object has no attribute 'Foo'

有人看到我在做什么错吗?

Anyone see what I'm doing wrong?

推荐答案

class Foo必须在非酸洗环境中可通过同一路径导入,以便可以重新实例化酸洗的对象.

class Foo must be importable via the same path in the unpickling environment so that the pickled object can be reinstantiated.

我认为您的问题是,您在作为主要模块(__name__ == "__main__")执行的模块中定义了Foo. Pickle会将序列化路径(而不是类对象/定义!!!)序列化为Foo,就像在主模块中一样. Foo不是主要的unpickle脚本的属性.

I think your issue is that you define Foo in the module that you are executing as main (__name__ == "__main__"). Pickle will serialize the path (not the class object/definition!!!) to Foo as being in the main module. Foo is not an attribute of the main unpickle script.

在此示例中,您可以在解腌脚本中重新定义class Foo,它应该也可以解粘.但实际上是要有一个在两个脚本之间共享的公用库,并且可以通过同一路径使用.示例:在foo.py

In this example, you could redefine class Foo in the unpickling script and it should unpickle just fine. But the intention is really to have a common library that is shared between the two scripts that will be available by the same path. Example: define Foo in foo.py

简单示例:

$ PROJECT_DIR/foo.py

class Foo(object):
    pass

$ PROJECT_DIR/picklefoo.py

import cPickle
from foo import Foo

def pickleObject():
    obj = Foo()
    savefile = open('pickle.txt', 'w')
    cPickle.dump(obj, savefile, cPickle.HIGHEST_PROTOCOL)


pickleObject()

$ PROJECT_DIR/unpicklefoo.py

import cPickle

savefile = open('pickle.txt', 'r')
obj = cPickle.load(savefile)
...

这篇关于取消拾取对象时发生AttributeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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