繁体   English   中英

如何序列化 Python 对象的位置和非位置参数?

[英]How to serialise both positional and non-positional arguments of Python objects?

我如何在下面序列化test

class Foo:
    a = 0
    b = {}

    def __init__(self, a, b=None):
        self.a = a

        if b:
            self.b = b


test = Foo(1)
test.b['c'] = 2

所以输出是:

{"a": 1, "b": {"c": 2}}

我试过了:

print(json.dumps(test, default=lambda x: x.__dict__))

但它返回:

{"a": 1}

我知道test.b['c'] = 2不会将bc添加到Foo.__dict__ ,这可能就是为什么 lambda 中的x.__dict__没有选择它们的原因。 答案之一是:

  1. 不要将键值对分配给任意对象; 请改用setattr
  2. 不要定义任意类,如果它的属性集可以在运行时演化; 改用简单的dict

这里的问题是test.b不是实例变量。 因此,当您使用json.dumps序列化对象test ,它根本找不到实例变量b

如果您重新定义构造函数,如下所示:

class Foo:
    a = 0 #this is not instance variable - this is a class variable
    b = {} #this is not instance variable - this is a class variable

    def __init__(self, a, b=None):
        self.a = a
        self.b = {} #declared the instance variable b also
        if b:
            self.b = b


test = Foo(1)
test.b['c'] = 2

现在,如果您运行,您将获得所需的输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM