打印时出现UnicodeEncodeError

时间:2014-03-26 14:50:51

标签: python error-handling encode

我有一个SomeClass类,我想在调试时打印这个类:

def __repr__(self):
    print type(self.id)
    print type(self.cn_name)
    print type(self.name)
    print type(self.finished)
    return u'''
    Bangumi id: %s
    Chinese Name: %s
    Original Name: %s
    Finished or Not: %s''' % (self.id, self.cn_name, self.name, self.finished)

我在下面得到以下信息:

>>> print anime.__repr__
<type 'int'>
<type 'unicode'>
<type 'unicode'>
<type 'int'>
Traceback (most recent call last):

File "<debugger>", line 1, in <module>
print anime.__repr__
UnicodeEncodeError: 'ascii' codec can't encode characters in position 45-50: ordinal not in range(128)

这是什么意思?我应该如何恢复它?

1 个答案:

答案 0 :(得分:1)

__repr__方法必须返回字节字符串对象;一个str。您正在返回一个unicode对象,并且Python使用ASCII编解码器隐式编码它,以强制它为字符串。

顺便说一句,如果您实际上调用 anime.__repr__(),就不会发生这种情况。相反,你只是引用方法对象,其表示包括repr(anime)字符串,它是执行编码的repr()函数。

您可以通过不从方法返回Unicode来解决此问题。将返回值明确编码为str

添加__unicode__方法来创建Unicode字符串。见Python __str__ versus __unicode__

相关问题