繼承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.uj5u.com/houduan/192838.html
標籤:Python
上一篇:Python爬取安居客租房資料,設定排除自己條件以外的資料
下一篇:類的“組合”
