加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 21:48:13 所属栏目:Python 来源:网络整理
导读:将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=

将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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读