面向对象和pickle模块结合
程序员文章站
2022-03-22 12:05:23
面向对象和pickle模块相关 1.面向对象: class 类名: def __init__(self,参数1,参数2): self.对象的属性1 = 参数1 self.对象的属性2 = 参数2 def 方法名(self):pass def 方法名2(self):pass 对象名 = 类名(1,2) ......
面向对象和pickle模块相关
1.面向对象:
class 类名:
def init(self,参数1,参数2):
self.对象的属性1 = 参数1
self.对象的属性2 = 参数2
def 方法名(self):pass
def 方法名2(self):pass
对象名 = 类名(1,2) #对象就是实例,代表一个具体的东西
2.pickle模块:
只能是python语言遵循的一种数据转化格式,只能在python语言中使用。
支持python所有的数据类型,包括实例化对象。pickle模块是将python所有的数据结构以及对象等转化成bytes类型,然后还可以反序列化还原回去。
用于网络传输:dumps、loads
用于文件写读:dump、load
3.面向对象和pickle模块结合:
1.使用pickle存取自定义类的对象的方式 #前提:必须有类 #通过pickle 存储和读取对象 class course: def __init__(self,name,period,price): self.name = name self.period = period self.price = price python = course('python','6 week',1800) linux = course('linux','5 week',1500) go = course('go','4 week',1200) import pickle with open('pickle_file','ab') as f: pickle.dump(python,f) pickle.dump(linux,f) pickle.dump(go,f) with open('pickle_file','rb') as f: while true: try: obj = pickle.load(f) print(obj.name,obj.period,obj.price) except eoferror: break 2.自定义pickle,借助pickle模块来完成简化的dump和load # pickle dump # 打开文件 # 把数据dump到文件里 # pickle load # 打开文件 # 读数据 # 对象 = mypickle('文件路径') # 对象.load() 能拿到这个文件中所有的对象 # 对象.dump(要写入文件的对象) ##1: import pickle class mypickle: def __init__(self,path): self.file = path def dump(self,obj): with open(self.file, 'ab') as f: pickle.dump(obj, f) def load(self): with open(self.file,'rb') as f: while true: try: yield pickle.load(f) except eoferror: break pic = mypickle('pickle_file') s1 = stack() #利用上面的栈 s1.put('aaa') s1.put(123) s1.put(456) pic.dump(s1) s2 = stack() s2.put('bbb') s2.put(888) s2.put(999) pic.dump(s2) for i in pic.load(): print(i.l) # ['aaa', 123, 456] # ['bbb', 888, 999] ##2: load(self)与上面略有不同 import pickle class mypickle: def __init__(self,path): self.file = path def dump(self,obj): with open(self.file, 'ab') as f: pickle.dump(obj, f) def load(self): l = [] with open(self.file,'rb') as f: while true: try: l.append(pickle.load(f)) except eoferror: break return l pic = mypickle('pickle_file') pic.dump('aaa') pic.dump('bbb') ret = pic.load() print(ret) #['aaa', 'bbb']