2013-08-30 82 views
1

有人能解釋我爲什麼在下面的例子中,print a 引發異常,而a.__str__()不是?Python unicode錯誤

>>> class A: 
... def __init__(self): 
...  self.t1 = "čakovec".decode("utf-8") 
...  self.t2 = "tg" 
... def __str__(self): 
...  return self.t1 + self.t2 
... 
>>> a = A() 
>>> print a 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
UnicodeEncodeError: 'ascii' codec can't encode character u'\u010d' in position 0: ordinal not in range(128) 
>>> a.__str__() 
u'\u010dakovectg' 
>>> print a.__str__() 
čakovectg 

回答

6

在Python 2 str必須返回一個ASCII字符串。當你直接調用__str__時,你跳過了Python將__str__的輸出轉換爲ASCII字符串的步驟(實際上你可以從__str__返回任何你想要的東西,但是你不應該這麼做)。 __str__不應該返回一個unicode對象,它應該返回str對象。

這裏的東西,你可以做,而不是:

In [29]: class A(object): 
    ...:  def __init__(self): 
    ...:   self.t1 = u"c∃".encode('utf8') 
    ...:  def __str__(self): 
    ...:   return self.t1 
    ...:  

In [30]: a = A() 

In [31]: print a 
c∃ 

In [32]: str(a) 
Out[32]: 'c\xe2\x88\x83' 

In [33]: a.__str__() 
Out[33]: 'c\xe2\x88\x83'