python持久化对象
通过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原来对象依赖的库,就可以调用对象所有的属性、方法: