[英]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.