继承json模块,重用模块中类的方法并派生出新的功能

 

  例:使用json模块序列化字符串

import json
from datetime import datetime, date

dict1 = {
    # 'time1': str(datetime.now())
    'time1': datetime.now(),
    'name': 'orange'
}

res = json.dumps(dict1)
# 无法序列datetime.now()格式,报错
print(res)    # TypeError: Object of type datetime is not JSON serializable

  执行结果:

TypeError: Object of type datetime is not JSON serializable

 

  # 报错原因:在原来json模块中可序列化的数据类型有限,在此例中datetime.now()无法被序列化

  # 解决方法:在原模块下可以继承并重写某些功能(不止json模块,其他模块中的类方法也可继承并重写

import json
from datetime import datetime

# 自定义一个类
class MyJson(json.JSONEncoder): # datetime.now() ---> o # 重写json模块中JSONEncoder类的方法 def default(self, o): # isinstance: 判断一个对象是否是一个类的实例 if isinstance(o, datetime): # True return datetime.strftime(o, '%Y-%m-%d %X') else: return super().default(self, o) dict1 = { # 'time1': str(datetime.now()) 'time1': datetime.now(), 'name': 'orange' } # 指定自定义的一个MyJson 派生类 # cls=自定义的类 res = json.dumps(dict1, cls=MyJson) print(res)

  执行结果:

{"time1": "2020-10-26 20:48:44", "name": "orange"}
内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/jsxxd/p/13881132.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!