标签:%s lambda book print tom ini 类别 turn init
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))
将实例对象编码成为json串的2种方式
标签:%s lambda book print tom ini 类别 turn init
原文地址:https://www.cnblogs.com/King-Tong/p/12169223.html