1:__new__:
__init__是初始化方法,__new__是构造方法,实例化过程先执行__new__开辟一个内存空间,再执行__init__
单例模式:一个类只有一个实例:
class Foo: __os = None def __init__(self,name,age): self.name = name self.age =age self.lst = [name] def __new__(cls, *args, **kwargs): if cls.__os == None: cls.__os = object.__new__(cls) return cls.__os ret1 = Foo('a',14) ret2 = Foo('b',15) print(ret1.lst,ret2.lst)
2:模块
1.别人写好的模块,放在文件中
2.内置模块,pychar安装时自带的模块
3.第三方模块,拓展模块,需要自己下载安装的模块
4,自定义模块:自己写的py文件
3:序列化模块:
1.序列:字符串,列表,字典,bytes
2.什么叫序列化:把数据类型转化为字符串,bytes
3.什么情况下使用:1.数据类型要进行文件存储时,2,数据类型进行网络传输时
4: 序列化以及反序列化:json
json 的优点:全语言通用
缺点:支持较少的数据类型:只支持列表,字典,数字,字符串,并字典的key必须是字符串.
import json dic = {'a':12,'name':'黎明'} os = json.dumps(dic,ensure_ascii=False) #序列化过程 print(os,type(os)) ds = json.loads(os) #反序列化 print(ds,type(ds))
5:pickle
import pickle dic = {'a':12,'name':'黎明',12:('地方',12)} rer = pickle.dumps(dic) print(rer,type(rer)) ret = pickle.loads(rer) print(ret,type(ret))
6:序列化写入文件:
import json dic = {'a':12,'name':'黎明'} dict = json.dumps(dic) with open('t1.txt','a',encoding='utf-8') as f1: f1.write(dict) with open('t1.txt',encoding='utf-8') as f: account = f.read() ocd = json.loads(account) print(ocd)
7.dump,load完全是只与文件操作:
import json dic = {'a':12,'name':'黎明'} with open('t1.txt','w',encoding='utf-8') as f: json.dump(dic,f) with open('t1.txt','r',encoding='utf-8') as f: ods = json.load(f) print(ods)
8.往文件中写入多个字典: