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
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.