簡體   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