我试图重写我的班级的 str 方法,这是我的代码:
# encoding: utf8
import json
class Test(object):
def __str__(self):
d = {
'foo': u'中文'
}
return json.dumps(d, ensure_ascii=False)
test = Test()
print test.__str__()
print test
让我感到困惑的是print test.__str__()
工作正常,但print test
导致异常:
Traceback (most recent call last):
File "test.py", line 17, in <module>
print(test)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 9-10: ordinal not in range(128)
python test.py 0.05s user 0.03s system 96% cpu 0.078 total
python版本2.7.12
答案 0 :(得分:2)
__str__
必须返回字符串值。如果您返回unicode
对象,它将自动编码为ASCII。
明确编码:
class Test(object):
def __str__(self):
d = {
'foo': u'中文'
}
return json.dumps(d, ensure_ascii=False).encode('utf8')
就个人而言,我不会使用__str__
方法来提供JSON编码。请改为选择其他方法名称,例如tojson()
。