2017-08-10 74 views
0

我想了一个简单的程序Python中的Json转储不打印值

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

这与模块json完全没有关系。

ur.__dict__是一个空字典,因为只有实例属性保存在实例中。

unified_response类仅具有类属性,因此ur.__dict__是一个空字典,它将json.dumps转换为空字符串。

比较print unified_response.__dict__print ur.__dict__的输出。


作为一个方面说明:

ur.preprocess.append(preprocessValDict)

访问(尤其是修改)类的属性通过一个实例被认为是不好的做法,因为它可以导致难以发现的错误。