引入shelve模塊,並自定義一個類python
>>> import shelve >>> class Person: def __init__(self,name,age): self.name=name self.age=age def __repr__(self): return '%s %d' %(self.name,self.age) def Speak(self): print('我是:%s,年齡%d' %(self.name,self.age))
實例化一個Person類對象列表peoplecode
>>> people=[Person('王菲',47),Person('柳巖',36),Person('范冰冰',37)] >>> people [王菲 47, 柳巖 36, 范冰冰 37]
用shelve序列化people列表對象
>>> with shelve.open (r'd:\python\mydata') as s: s['mydata']=people
反序列化people列表it
>>> people=[] >>> people [] >>> with shelve.open (r'd:\python\mydata') as s: people=s['mydata'] >>> people [王菲 47, 柳巖 36, 范冰冰 37] >>> for p in people: p.Speak() 我是:王菲,年齡47 我是:柳巖,年齡36 我是:范冰冰,年齡37
一切正常,正是咱們須要的結果。實踐發現,不論是用shelve仍是pickle,反序列化時,必定要有類定義。class