I'm playing around with class inheritances and I'm stuck on how to pickle data in the class dictionary.
If dump only the dictionary part of self, when I load the dictionary back to self, self takes on a dict type instead of a class. But if I pickle the whole class then I get an error.
Error
pickle.PicklingError: Can't pickle <class 'main.model'>: it's not the same object as main.model
Code
import os, pickle
class model(dict):
def __init__( self ):
pass
def add( self, id, val ):
self[id] = val
def delete( self, id ):
del self[id]
def save( self ):
print type(self)
pickle.dump( dict(self), open( "model.dict", "wb" ) )
def load( self ):
print 'Before upacking model.dic, self ==',type(self)
self = pickle.load( open( "model.dict", "rb" ) )
print 'After upacking model.dic, self ==',type(self)
if __name__ == '__main__':
model = model()
#uncomment after first run
#model.load()
#comment after first run
model.add( 'South Park', 'Comedy Central' )
model.save()
savefunction the only thing that changes? Btw, Inload, usingself = pickle.load(...)merely changes the local variable calledself, it doesn't actually change themodelobject.selfthen do I need to worry about this at all?loadmethod exits the unpickled stat is lost. Marwan Alsabbagh's answer below shows a much better way of pickling and unpickling the object.