python持久化物件

2022-05-02 04:03:07 字數 530 閱讀 1425

通過shelve模組即可持久化物件

import shelve

import numpy as np

def writeobj(name,obj):

with shelve.open('object') as db:

db[name]=obj

def readobj(name):

try:

with shelve.open('object') as db:

return db[name]

except baseexception:

return none

if __name__ == '__main__':

a=np.array([1,2,3])

writeobj('arr',a)

print(readobj('arr'))

pass

吧乙個物件持久化之後,不需要import原來物件依賴的庫,就可以呼叫物件所有的屬性、方法:

python 物件持久化

print open persondb.dat rb read testdemo2.py 讀取資料庫 載入乙個例項的時候,類極其模組的檔案都必須匯入 該類的例項再次載入的時候,對類的源 檔案的修改會自動選取 import testdemo import shelve db shelve.open p...

python物件持久化

pickle模組 import pickle person s pickle.dumps person p pickle.loads s pickle.dump person,open pickle db wb p pickle.load open pickle db rb print p prin...

物件持久化

物件持久化 ifname main read scores pickle 將字典表序列化成字串pickle.dumps 字串變回字典用pickle.loads s import pickle person s pickle.dumps person 序列化 p pickle.loads s 恢復 序...