• 将实例对象编码成为json串的2种方式


    import json
    class Book():
        def __init__(self,id,category,year,author):
            self.id=id
            self.category=category
            self.year=year
            self.author=author

        def print_sth(self):
            print( "书的编号是%s类别是%s年代%s作者是%s"%(self.id,self.category,self.year,self.author))
     
        def obj_detail(self,obj):
            return {
                        "id":obj.id,
                        "category":obj.category,
                        "year":obj.year,
                        "author":obj.author
                          }
    Book1=Book(1,2019,"prose","Tom")
    js=json.dumps(Book1,default=Book1.obj_detail)
    print(type(js))
    print(js)
    Book1.print_sth()
     
    方式二
    import json
    class Book():

        def __init__(self,id,category,year,author):
            self.id=id
            self.category=category
            self.year=year
            self.author=author
     
    Book1=Book(1,2019,"prose","Tom")
    js=json.dumps(Book1,default=lambda Book1:Book1.__dict__)
    print(js)
    print(type(js))
  • 相关阅读:
    冗余链接-684-并查集
    Chrome浏览器进程
    BFC布局规则
    Front-end 前端优化总结
    Flex弹性布局
    Browse兼容性问题
    组合关系与组合模式
    YUI3组件框架之plugin
    javascript数据类型及转换
    矩阵打印
  • 原文地址:https://www.cnblogs.com/King-Tong/p/12169223.html
Copyright © 2020-2023  润新知