Python:为什么__str__不能调用递归?

Python:为什么__str__不能调用递归?,第1张

概述将dict转换为JSON对象时遇到一些麻烦.我有这门课:class ServerResponse(object): status = None code = None message = None data = None OK_STATUS = True ERROR_STATUS = False

将dict转换为JSON对象时遇到一些麻烦.我有这门课:

class ServerResponse(object):    status = None    code = None    message = None    data = None    OK_STATUS = True    ERROR_STATUS = False    OK_CODE = 200    def __init__(self,status=OK_STATUS,code=OK_CODE,message=None,data=None,*args,**kwargs):        self.status = status        self.code = code        self.message = message        self.data = data    def to_dict(self):        fIElds = {            "status": self.status,"code": self.code,"message": self.message,"data": str(self.data),}        return fIElds    def to_Json(self):        return Json.dumps(self.to_dict())    def __str__(self):        return self.to_Json()

我用这个类来生成服务器答案.

from server_response import ServerResponse as Response...return_data = {}for (name,content) in result.items():    if not prevIoUs_hashes or clIEnt.is_data_change(prevIoUs_hashes[name],data['hash']):        return_data[name] = Response(data=content)    else:        return_data[name] = Response(code=201,message="Data has not changed")response = Response(data=return_data)...self.write(str(response))

从服务器回答我得到下一个JsON

{u'status': True,u'message': None,u'code': 200,u'data': u"{'clIEnt': <server_response.ServerResponse object at 0x14e9710>,'service': <server_response.ServerResponse object at 0x14e90d0>}"}

为什么__str__函数不会递归调用?最佳答案从这个程序:

class Foo(object):    def __repr__(self):        return "REPR"    def __str__(self):        return "STR"x = {}x['clIEnt'] = Foo()print str(x)print repr(x)

你可以看到dict总是在其成员上调用repr,无论是否在dict上使用了str或repr. 总结

以上是内存溢出为你收集整理的Python:为什么__str__不能调用递归?全部内容,希望文章能够帮你解决Python:为什么__str__不能调用递归?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1205283.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存