2014-03-26 63 views
0

我有一個類SomeClass的,我想打印這個類在調試:了UnicodeEncodeError在打印過程中

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) 

這是什麼意思?我應該如何恢復它?

+0

您的__repr__方法正確地返回了一個Unicode字符串,但您的控制檯或終端未正確配置,並且Python試圖將結果編碼爲ASCII。 –

+0

你使用什麼終端或控制檯?請注意,某些IDE控制檯無法正確地告訴Python要使用哪種編碼。 –

+0

請注意,您**不應該從'__repr__' **返回Unicode; Python 2中的所有其他東西總是返回字節串,參見['__repr__'文檔](http://docs.python.org/2/reference/datamodel.html#object.__repr__)。這是一個單獨的問題;您的控制檯也不會打印任何其他的unicode。 –

回答

1

__repr__方法必須返回一個字節的字符串對象;一個str。您將返回一個unicode對象,並且Python使用ASCII編解碼器隱式編碼它,以將其強制爲字符串。順便說一下,如果你真的叫做anime.__repr__(),這不會發生;相反,您只是指方法對象,其表示形式包括repr(anime)字符串,而repr()函數執行編碼。

您可以通過不從方法返回Unicode來解決此問題。明確地將返回值編碼爲str

添加一個__unicode__方法來創建一個Unicode字符串。請參閱Python __str__ versus __unicode__