私はクラスの継承をいじっていて、クラス辞書でデータをピクルする方法にこだわっています。
自己の辞書部分のみをダンプする場合、辞書を自己にロードすると、自己はクラスではなく辞書型になります。しかし、クラス全体をピクルすると、エラーが発生します。
エラー
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()