Python 如何使对象本身可序列化?

Python 如何使对象本身可序列化?,python,python-3.x,Python,Python 3.x,如何使对象可序列化?以下代码: # -*- coding: utf-8 -*- import json import pickle import bson class A(object): def __init__(self): self.a = 'a' def __reduce__(self): return type(self), (self.a,) try: print(pickle.dumps({'a': A()})) #

如何使对象可序列化?以下代码:

# -*- coding: utf-8 -*-
import json
import pickle
import bson


class A(object):
    def __init__(self):
        self.a = 'a'

    def __reduce__(self):
        return type(self), (self.a,)

try:
    print(pickle.dumps({'a': A()}))  # Ok
except Exception as exc:
    print(exc)

try:
    print(json.dumps({'a': A()}))  # Error
except Exception as exc:
    print(exc)

try:
    print(bson.BSON.encode({'a': A()}))  # Error
except Exception as exc:
    print(exc)
制作:

b'\x80\x03}q\x00X\x01\x00\x00\x00aq\x01c__main__\nA\nq\x02h\x01\x85q\x03Rq\x04s.'
<__main__.A object at 0x7f3a06fef048> is not JSON serializable
Cannot encode object: <__main__.A object at 0x7f3a06fef048>
b'\x80\x03}q\x00X\x01\x00\x00\x00aq\x01c\uuuuuu main\uuuuuu\nA\nq\x02h\x01\x85q\x03Rq\x04s。'
JSON不可序列化
无法对对象进行编码:
我不想编写自己的JSON、BSON等序列化程序,我需要使对象JSON/BSON/。。。可自行序列化


可能吗?如何?

您是否尝试过从
list
dict
中对您的类进行子类化,以实现您的目标?@Alfe如果子类化
str
等,则该方法有效是的。但我不想这样做,因为我的对象将无法完全实现
str
list
等接口。然后,对于json,您可以看看(不创建私有de/encoder,从类本身就不可能,但创建私有de/encoder很容易)。对于json,您可以使用