[英]Trying to pickle object instance throws pickling error
I am trying to pickle class instance, referring to http://stefaanlippens.net/python-pickling-and-dealing-with-attributeerror-module-object-has-no-attribute-thing.html However gives me 我正在尝试腌制类实例,请参阅http://stefaanlippens.net/python-pickling-and-dealing-with-attributeerror-module-object-has-no-attribute-thing.html,但是给了我
try.py try.py
import pickle
class abc(object):
def __init__(self):
self.a = 10
def save(self):
pickle.dump(self,open("try.pkl","wb"))
if __name__ == '__main__':
a = abc()
abc.__module__ = "try"
a.save()
pickle.PicklingError: Can't pickle <class 'try.abc'>: it's not the same object as try.abc
Am I making a mistake here ? 我在这里犯错了吗? Is there a different solution to pickle object for stand alone purpose
是否有其他解决方案来腌制对象以用于独立用途
If you take away your abc.__module__ = "try"
everything works fine. 如果您拿走了
abc.__module__ = "try"
一切正常。
import pickle
class abc(object):
def __init__(self):
self.a = 10
def save(self):
pickle.dump(self,open("try.pkl","wb"))
if __name__ == '__main__':
a = abc()
a.save()
# proof it worked
with open('try.pkl','rb') as pkl_file:
b = pickle.load(pkl_file)
print(b.a)
I've added code at the end to reload the data and print it to show it was successful. 我已经在代码末尾添加了代码以重新加载数据并打印它以表明它是成功的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.