简体   繁体   English

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

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

How can I serialise test below:我如何在下面序列化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

so that the output is:所以输出是:

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

I've tried:我试过了:

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

but it returns:但它返回:

{"a": 1}

I understand that test.b['c'] = 2 does not add b or c to Foo.__dict__ , which is probably why x.__dict__ in the lambda doesn't pick them up.我知道test.b['c'] = 2不会将bc添加到Foo.__dict__ ,这可能就是为什么 lambda 中的x.__dict__没有选择它们的原因。 So is the answer one of:答案之一是:

  1. Do not assign key-value pairs to arbitrary objects;不要将键值对分配给任意对象; use setattr instead.请改用setattr
  2. Do not define arbitrary classes, if its property set can evolve at runtime;不要定义任意类,如果它的属性集可以在运行时演化; use a simple dict instead.改用简单的dict

The problem here is test.b is not a instance variable.这里的问题是test.b不是实例变量。 So when you serialize the object test using json.dumps , its not finding an instance variable b at all.因此,当您使用json.dumps序列化对象test ,它根本找不到实例变量b

If you redefine the constructor like below:如果您重新定义构造函数,如下所示:

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

Now, if you run you get the desired output.现在,如果您运行,您将获得所需的输出。

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

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