zoukankan      html  css  js  c++  java
  • 序列化模块

    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.往文件中写入多个字典:

  • 相关阅读:
    报表自动化: 商业智能背后的秘密
    谈谈个人对 TDD (测试驱动开发) 的理解
    初识 Inception
    从软件生命周期看应用安全(网络安全)
    Spring JPA save 实现主键重复抛异常
    QMdiArea及QMdiSubWindow实现父子窗口及布局方法
    QTcpServer实现多客户端连接
    C++设计模式
    QTreeView/QTableView中利用QStandardItem实现复选框三种形态变化
    Qt富文本编辑器QTextDocument
  • 原文地址:https://www.cnblogs.com/lijinming110/p/9581152.html
Copyright © 2011-2022 走看看