我正在尝试一个简单的程序
import json
class unified_response():
trinitiversion="3"
preprocess = []
if __name__ == '__main__':
ur = unified_response()
preprocessValDict = dict()
preprocessValDict["input"] = "some string"
preprocessValDict["correct"] = " correct some string"
ur.preprocess.append(preprocessValDict)
s = json.dumps(unified_response.__dict__)
print s
s = json.dumps(ur.__dict__)
print s
打印第一个打印语句
{"preprocess": [{"input": "some string", "correct": " correct some string"}], "trinitiversion": "3", "__module__": "__main__", "__doc__": null}
打印第二个print语句
{}
为什么第二个对象不打印任何值?
答案 0 :(得分:0)
这与json
模块完全无关。
ur.__dict__
是一个空字典,因为实例中只保存了实例属性。
unified_response
类只有类属性,因此ur.__dict__
是一个空字典,json.dumps
转换为空字符串。
比较print unified_response.__dict__
和print ur.__dict__
的输出。
作为旁注:
ur.preprocess.append(preprocessValDict)
通过实例访问(尤其是修改)类属性被认为是一种不好的做法,因为它可能导致难以发现的错误。