将继承类中的python父类序列化为JSON - 可能还是愚蠢?

时间:2014-03-24 12:25:10

标签: python json serialization

我知道有很多关于JSON序列化的问题,但我似乎还没有理解它。

鉴于以下课程:

import json

class BaseMongoObject(object):
    def __init__(self):
        pass

    def jsonify(self):
        return json.dumps(self, default=lambda o: o.__dict)

以下派生类:

from assetfacts import AssetFacts
from bmo import BaseMongoObject

class Asset(BaseMongoObject):
    def __init__(self):
        BaseMongoObject.__init__(self)
        self.facts = AssetFacts()
        self.serial = None

尝试使用以下测试代码调用asset.jsonify()

from asset import Asset

def test_me():
    a = Asset()
    a.serial = '123asdf'

    print a.jsonify()


if __name__ == '__main__':
    test_me()

产生以下内容:

    Traceback (most recent call last):
  File "../bin/test.py", line 17, in <module>
    test_me()
  File "../bin/test.py", line 13, in test_me
    print a.jsonify()
  File "/Users/vlazarenko/MP/ac/lib/bmo.py", line 8, in jsonify
    return json.dumps(self, default=lambda o: o.__dict)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 250, in dumps
    sort_keys=sort_keys, **kw).encode(obj)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "/Users/vlazarenko/MP/ac/lib/bmo.py", line 8, in <lambda>
    return json.dumps(self, default=lambda o: o.__dict)
AttributeError: 'Asset' object has no attribute '_BaseMongoObject__dict'

我会在哪里脑力下降这个?理想情况下,我不想被大量的继承所困扰,只是从顶部开始序列化。

1 个答案:

答案 0 :(得分:1)

您希望jsonify self.__dict__代替:

def jsonify(self):
    return json.dumps(self, default=lambda o: o.__dict__)

在子类中只有{em>以开头并带有双下划线的名称为mangled to protect them from accidental overriding.__dict被重写为._BaseMongoObject__dict