我已经编写了一个类,我需要能够使用python的pickle模块进行pickle和unpickle。酸洗似乎工作正常,但当我解开时我得到一个错误。我可以使用下面给出的更简单的类来复制错误:
class TestClass(object):
def __init__(self):
self.teststr = 'Hello'
def __str__(self):
return self.teststr
def __repr__(self):
return self.teststr
def test(self):
return 'test: {0}'.format(self.teststr)
如果我在python会话中运行以下代码,一切正常:
import pickle as pi
mytest = TestClass()
fs ='C:/Desktop/pickle'
f = open(fs, 'w')
pi.dump(mytest, f)
f.close()
f = open(fs, 'r')
unpi = pi.load(f)
f.close()
print unpi
但是如果我重新启动python,并运行以下代码:
import pickle as pi
fs ='C:/Desktop/pickle'
f = open(fs, 'r')
unpi = pi.load(f)
我收到错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Programs\Coding\Languages\Python\Anaconda_32bit\Conda\lib\pickle.py",
line 1378, in load
return Unpickler(file).load()
File "C:\Programs\Coding\Languages\Python\Anaconda_32bit\Conda\lib\pickle.py",
line 858, in load
dispatch[key](self)
File "C:\Programs\Coding\Languages\Python\Anaconda_32bit\Conda\lib\pickle.py",
line 1090, in load_global
klass = self.find_class(module, name)
File "C:\Programs\Coding\Languages\Python\Anaconda_32bit\Conda\lib\pickle.py",
line 1126, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'TestClass'
如果我在新的python会话中重新定义TestClass对象并重新运行第二个代码块,我会得到一个不同的错误,所以没有帮助。
我意识到这个问题看起来像: link
但我认为不是,因为接受的答案似乎表明定义为self.a(而不仅仅是a)的属性将允许pickle正常工作?
我实际上需要能够将我的类与Apache Spark一起使用,它似乎只适用于可以腌制的对象。