我正在玩类继承,我被困在如何腌制类字典中的数据。
如果只转储 self 的字典部分,当我将字典加载回 self 时,self 采用 dict 类型而不是类。但是,如果我腌制整个班级,则会出现错误。
错误
pickle.PicklingError: Can't pickle <class 'main.model'>: it's not the same object as main.model
代码
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()