鱼C论坛

 找回密码
 立即注册
查看: 1965|回复: 3

python 内部类 如何序列化

[复制链接]
发表于 2021-11-17 16:34:08 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. class wordnet():
  2.     class word():
  3.         def __init__(self) -> None:
  4.             self.word = List
  5.             self.offset = int
  6.             self.pos = str

  7.     def __init__(self) -> None:
  8.         self.word_set = self.word()
  9.         self.hyper = self.word()
  10.         self.hypon = self.word()
  11.         self.partOf = self.word()
  12.         

  13.     def output(self):
  14.         with open('data.json', 'a', encoding='utf-8') as d:
  15.             print(self.__dict__)
  16.             jsonstr = json.dumps(self.__dict__)
  17.             d.write(jsonstr + '\n')
复制代码



我想用 self.__dict__ 序列化 wordnet 的实例,但是内部类 word 无法被序列化,输出
  1. {'word_set': <__main__.wordnet.word object at 0x000001C3B3B09B38>, 'hyper': <__main__.wordnet.word object at 0x000001C3AFDAD7F0>, 'hypon': <__main__.wordnet.word object at 0x000001C3B4946080>, 'partOf': <__main__.wordnet.word object at 0x000001C3B49461D0>}
复制代码


应该怎么解决?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-11-17 16:56:49 | 显示全部楼层
json.dump
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-11-17 17:53:27 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-11-18 09:10:50 | 显示全部楼层
2个方法
1 使用框架 如fastapi  只要你的对象实现了keys方法和__getitem__方法 它会帮你序列化
2 使用json.dumps   它有个cls参数需要你定义一个default方法 具体百度 传进去之后就可以序列化指定的类
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-1 06:44

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表