You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类方法写入JSON文件时报Rectangle对象不可序列化错误

错误根因
  • JSON 模块默认仅支持序列化字典、列表、字符串、数字等Python内置基础类型,无法直接序列化自定义的Rectangle类实例
  • 现有代码逻辑存在三处方法定义/调用错误:
    1. Base.to_json_string设计接收字典列表入参,但实际传入了Rectangle实例列表,未做实例到属性字典的转换
    2. to_json_string方法未添加@staticmethod装饰器,作为普通类内方法调用时会触发参数匹配错误
    3. save_to_file中错误使用cls(Base.to_json_string(list_objs))写法,该写法意图是用JSON字符串实例化当前类,和写入文件的需求完全不符
修复方案
  1. 给Rectangle类新增实例转属性字典的方法
class Rectangle(Base):
    # 原有__init__等逻辑保留,新增以下方法
    def to_dictionary(self):
        return {
            "id": self.id,
            "width": self.width,
            "height": self.height,
            "x": self.x,
            "y": self.y
        }
  1. 修改Base类的方法定义与调用逻辑
import json
class Base:
    @staticmethod
    def to_json_string(list_dictionaries):
        if not list_dictionaries:
            return "[]"
        return json.dumps(list_dictionaries)

    @classmethod
    def save_to_file(cls, list_objs):
        filename = f"{cls.__name__}.json"
        # 先将所有实例转换为字典列表
        dict_list = [obj.to_dictionary() for obj in list_objs] if list_objs else []
        # 生成JSON字符串后直接写入文件
        with open(filename, "w", encoding="utf-8") as f:
            f.write(cls.to_json_string(dict_list))

修改后运行测试代码即可输出预期的JSON内容。

内容的提问来源于stack exchange,提问作者seahorse-code

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:24:03