在Python中,如何对使用__slots__的对象使用json.dumps?

1 投票
1 回答
5157 浏览
提问于 2025-04-18 18:45

当我尝试在一个使用了 __slots__ 的类的对象上使用 json.dumps 时,我会遇到“...无法序列化为JSON”的错误,或者可能会出现一个 AttributeError,提示 __dict__ 缺失。我该如何解决这个问题呢?看起来 __slots__ 应该告诉解释器使用一个虚拟字典来保持兼容性。

import json

class Foo:
     __slots__ = ["bar"]
     def __init__(self):
         self.bar = 0

json.dumps(Foo())

1 个回答

3

普通的 json.dumps() 方法不支持自定义类,这一点是肯定的。无论这些类是否使用了 __slots__,都没有关系。

处理自定义类的一个常见方法是使用一个钩子(hook),这个钩子返回类的 __dict__ 属性,但在这里显然行不通。你需要找到其他方法来序列化这些对象。

一种方法是让这些对象有一个专门的方法:

class Foo:
     __slots__ = ["bar"]
     def __init__(self):
         self.bar = 0

     def json_serialize(self):
         return {'bar': self.bar}

然后在你的 default 钩子中使用这个方法:

json.dumps(Foo(), default=lambda o: o.json_serialize())

撰写回答