[英]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
不会将b
或c
添加到Foo.__dict__
,这可能就是为什么 lambda 中的x.__dict__
没有选择它们的原因。 答案之一是:
setattr
。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.