简体   繁体   English

python2.7 __str__打印时导致UnicodeEncodeError

[英]python2.7 __str__ cause UnicodeEncodeError when print

I tried to rewrite my class's str method, this is my code: 我试图重写类的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

what make me confused is that print test.__str__() works fine, but print test cause exception: 让我感到困惑的是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 version 2.7.12 python版本2.7.12

__str__ must return a string value. __str__ 必须返回一个字符串值。 If you return a unicode object instead, it'll be automatically encoded as ASCII. 如果返回一个unicode对象,它将被自动编码为ASCII。

Encode explicitly instead: 改为显式编码:

class Test(object):
    def __str__(self):
        d = {
            'foo': u'中文'
        }
        return json.dumps(d, ensure_ascii=False).encode('utf8')

Personally, I'd not use the __str__ method to provide a JSON encoding. 就个人而言,我不会使用__str__方法来提供JSON编码。 Pick a different method name instead, like tojson() . 选择一个不同的方法名称,例如tojson()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM